24 Most important JavaScript methods

As a JavaScript developer, it is important to be familiar with the various JavaScript methods available in the language. In this article, we will take a look at 24 of the most commonly used JavaScript methods. By understanding and utilizing these methods, you can take your development skills to the next level.

map()

The JavaScript map() method is used to create a new array populated with the results of calling a provided function on every element in the calling array. This is a powerful tool that can be used to perform many different operations on arrays.

const array = [11, 4, 9, 16, 25];

// pass a function to map
const map = array.map(x => x * 2);

console.log(map);
// expected output: Array [22, 8, 18, 32, 50]

reduce()

JavaScript reduce() method is used to apply a function to each element in an array (or array-like object) and reduce it to a single value. This is the most basic operation that can be performed on an array. It can be used with various JavaScript data types including arrays, objects, and strings. The reduce() method takes two arguments: the first is a callback function and the second is an optional initial value.

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);

console.log(sumWithInitial);
// expected output: 10

flat()

The JavaScript flat() method is used to flatten an array. The depth of the array can be specified as an optional parameter. A shallow copy of the array is made with flattened nested arrays replaced by references to their elements.

const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]

const arr2 = [0, 1, 2, [[[3, 4]]]];

console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]

filter()

The JavaScript filter() method is used to select elements from an array based on certain criteria. The criteria are specified in a callback function, which is executed for each element in the array. If the callback function returns true, the element is included in the resulting array. Otherwise, it is excluded.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

forEach()

The JavaScript forEach() method is used to execute a function on each element in an array. The JavaScript forEach method is similar to the for loop and the for-in loop. It can be used to iterate over arrays, objects, and functions.

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// expected output: "a"
// expected output: "b"
// expected output: "c"

findIndex()

JavaScript findIndex() method executes the provided callback function once for each element in the array until it finds an element that returns a truthy value from the callback. If such an element is found, findIndex() immediately returns the index of that element in the array. Otherwise, it returns -1.

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

find()

The JavaScript find() method returns the value of the first element in an array that passes a test provided by a callback function. It executes the callback function once for each element in the array until it finds a element that returns true. If such an element is found, find() immediately returns the value of that element. Otherwise, it returns undefined.

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

sort()

The JavaScript sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

concat()

The JavaScript concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// expected output: Array ["a", "b", "c", "d", "e", "f"]

fill()

The JavaScript fill() method is a static method of the built-in JavaScript Array object. It changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.

const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]

includes()

The JavaScript includes() method is used to determine whether an array includes a certain element. This method returns true if the array contains the element, and false otherwise. The includes() method is case-sensitive.

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

reverse()

The JavaScript reverse() method is used to reverse the order of the elements in an array. The first element becomes the last, and the last element becomes the first. This method does not change the original array.

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

some()

The JavaScript some() method is used to check if at least one element in an array passes a test implemented by a callback function. It returns a Boolean value.

const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true

every()

The JavaScript every() method is used to check if all the elements in an array pass the given condition. It returns a Boolean value: true if all items pass the test, false otherwise.

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

slice()

The JavaScript slice() method is used to extract a section of a string and return a new string. The original string is not modified. This method extracts parts of a string and returns the extracted part in a new string.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// expected output: Array ["camel", "duck"]

console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

indexOf()

The JavaScript indexOf() method is used to find the first occurrence of a specified value in a string. This method returns the index of the first occurrence of the specified value, or -1 if the value is not found.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// expected output: 1

// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4

console.log(beasts.indexOf('giraffe'));
// expected output: -1

split()

The JavaScript split() method is used to split a string into an array of substrings, and returns the new array. The original string is not modified.

const str = 'The quick brown fox jumps over the lazy dog.';

const words = str.split(' ');
console.log(words[3]);
// expected output: "fox"

const chars = str.split('');
console.log(chars[8]);
// expected output: "k"

const strCopy = str.split();
console.log(strCopy);
// expected output: Array ["The quick brown fox jumps over the lazy dog."]

assign()

The JavaScript assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget === target);
// expected output: true

replace()

The JavaScript replace() method is used to replace a specified value with another value in a string. This method does not change the original string, but instead returns a new string with the replaced values.

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replace('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

const regex = /Dog/i;
console.log(p.replace(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"

search()

The JavaScript search() method searches for a specified value in a string and returns the position of the match. If no match is found, it returns -1. This method is different from the indexOf() method in that it accepts a regular expression as an argument, rather than just a string.

const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

// any character that is not a word character or whitespace
const regex = /[^\w\s]/g;

console.log(paragraph.search(regex));
// expected output: 43

console.log(paragraph[paragraph.search(regex)]);
// expected output: "."

match()

The JavaScript match() method is used to search for a match between a regular expression and a string. This method returns an array of information or null if no match is found.

const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);

console.log(found);
// expected output: Array ["T", "I"]

valueOf()

The JavaScript valueOf() method is a way of getting the primitive value of a JavaScript object. The objects it can be called on are: Boolean, Number, and String objects. When called on an object, it returns the primitive value of the object.

const stringObj = new String('foo');

console.log(stringObj);
// expected output: String { "foo" }

console.log(stringObj.valueOf());
// expected output: "foo"

lastIndexOf()

The JavaScript lastIndexOf() method returns the position of the last occurrence of a specified value in a string. This method searches both forward and backward in a string, starting from the end of the string. If it finds the value, it returns the position of the value. Otherwise, it returns -1.

const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';

console.log(`The index of the first "${searchTerm}" from the end is ${paragraph.lastIndexOf(searchTerm)}`);
// expected output: "The index of the first "dog" from the end is 52"

flatMap()

The JavaScript flatMap() method first appeared in JavaScript with the release of ES2018. It is similar to the map() method, but it flattens the result instead of returning a new array. This can be useful if you need to convert a two-dimensional array into a one-dimensional array. The flatMap() method can also be used to merge two or more arrays.

const arr1 = [1, 2, [3], [4, 5], 6, []];

const flattened = arr1.flatMap(num => num);

console.log(flattened);
// expected output: Array [1, 2, 3, 4, 5, 6]
W3TWEAKS
Latest posts by W3TWEAKS (see all)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *