JavaScript arrays come equipped with a powerful set of built-in methods. Whether you're iterating, transforming, filtering, or searching, understanding these methods is crucial for efficient and clean coding. This article will cover all 22 essential array methods with practical examples, perfect for both beginners and those needing a quick refresher.
forEach(): Executing a Function for Each Array Element
Similar to a for loop but often with cleaner syntax, forEach() executes a provided function once for each array element. It's primarily used for its side effects (like logging or updating external variables) as it does not return a new array and its return value is undefined. It does not modify the array it is called on unless the callback function modifies it.
const arr = [1, 2, 3, 4];
arr.forEach(item => {
console.log(item);
});
Output:
1
2
3
4
includes(): Checking if an Array Contains a Specific Value
To efficiently check if an array contains a specific value without manual iteration, use includes(). It returns true if the array contains the element, and false
otherwise. It performs a strict equality (===
) check.
const arr = [1, 2, 3, 4];
console.log(arr.includes(2)); // output: true
console.log(arr.includes(7)); // output: false
filter(): Creating a New Array with Elements That Pass a Test
filter() creates a new array containing only the elements from the original array that satisfy a provided condition (a function that returns true or false). It does not modify the original array.
const arr = [1, 10, 5, 3, 6, 1, 32];
// Filter for items greater than or equal to 10
const filteredArray = arr.filter(num => num >= 10);
console.log(filteredArray); // output: [10, 32]
// Original array remains unchanged
console.log(arr); // output: [1, 10, 5, 3, 6, 1, 32]
map(): Creating a New Array by Transforming Each Element
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. It's commonly used for transforming data (e.g., doubling numbers, extracting properties from objects). It does not modify the original array.
const arr = [1, 2, 3, 4, 5, 6];
// Add one to every element
const oneAdded = arr.map(num => num + 1);
console.log(oneAdded); // output: [2, 3, 4, 5, 6, 7]
// Original array remains unchanged
console.log(arr); // output: [1, 2, 3, 4, 5, 6]
In frameworks like React, map() is frequently used to iterate over an array of data and return JSX elements for rendering lists.
reduce(): Reducing an Array to a Single Value (e.g., Summing Numbers)
The reduce() method executes a user-supplied "reducer" callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements is a single value. It takes an accumulator and the current value as arguments, plus an optional initial value for the accumulator. It does not modify the original array.
MDN Definition: The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
const arr = [1, 2, 3, 4, 5, 6];
// Sum all elements, starting accumulator at 0
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // output: 21
// Original array remains unchanged
console.log(arr); // output: [1, 2, 3, 4, 5, 6]
some(): Checking if at Least One Element Passes a Test
some() tests whether at least one element in the array passes the test implemented by the provided function. It returns true if it finds an element for which the function returns true; otherwise it returns false. It stops iterating as soon as a truthy value is found.
const arr = [1, 2, 3, 4, 5, 6];
// Check if at least one number is greater than 4
const hasGreaterThanFour = arr.some(num => num > 4);
console.log(hasGreaterThanFour); // output: true
every(): Checking if All Elements Pass a Test
every() tests whether all elements in the array pass the test implemented by the provided function. It returns true if the function returns true for every element, and false otherwise. It stops iterating as soon as a falsy value is found.
const arr = [1, 2, 3, 4, 5, 6];
// Check if all numbers are greater than 4
const allGreaterThanFour = arr.every(num => num > 4);
console.log(allGreaterThanFour); // output: false
// Check if all numbers are less than 10
const allLessThanTen = arr.every(num => num < 10);
console.log(allLessThanTen); // output: true
sort(): Sorting Array Elements In Place
The 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. This means numerical sorting requires a compare function. Warning: sort() modifies the original array.
const numArr = [1, 10, 5, 3, 6, 1, 32];
const alpha = ['e', 'a', 'c', 'u', 'y'];
// Sort numbers in ascending order
// Provide a compare function (a, b) => a - b
numArr.sort((a, b) => a - b);
console.log(numArr); // output: [1, 1, 3, 5, 6, 10, 32] (original array is modified)
// Sort strings in alphabetical (ascending) order (default behavior works)
alpha.sort();
console.log(alpha); // output: ['a', 'c', 'e', 'u', 'y'] (original array is modified)
// Sort numbers in descending order
numArr.sort((a, b) => b - a);
console.log(numArr); // output: [32, 10, 6, 5, 3, 1, 1]
Array.isArray(): Determining if a Value is an Array
This static method determines whether the passed value is an Array. It's useful for type checking before attempting to use array-specific methods on a variable.
console.log(Array.isArray({ hello: 'world' })); // false (it's an object)
console.log(Array.isArray(['hello', 'world'])); // true (it's an array)
console.log(Array.isArray('hello')); // false (it's a string)
push(): Adding One or More Elements to the End of an Array
The push() method adds one or more elements to the end of an array and returns the new length of the array. This method modifies the original array.
const arr = [1, 2, 3, 4, 5];
const newLength = arr.push(6);
console.log(arr); // output: [1, 2, 3, 4, 5, 6]
console.log(newLength); // output: 6
// You can push multiple items
arr.push(7, 8);
console.log(arr); // output: [1, 2, 3, 4, 5, 6, 7, 8]
pop(): Removing the Last Element from an Array
The pop() method removes the last element from an array and returns that removed element. This method modifies the original array. If the array is empty, undefined is returned.
const arr = [1, 2, 3, 4, 5, 6];
const poppedValue = arr.pop();
console.log(arr); // output: [1, 2, 3, 4, 5]
console.log(poppedValue); // output: 6
shift(): Removing the First Element from an Array
The shift() method removes the first element from an array and returns that removed element. This method modifies the original array. If the array is empty, undefined
is returned.
const arr = [1, 2, 3, 4, 5, 6];
const shiftedValue = arr.shift();
console.log(arr); // output: [2, 3, 4, 5, 6]
console.log(shiftedValue); // output: 1
unshift(): Adding One or More Elements to the Beginning of an Array
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. This method modifies the original array.
const arr = [2, 3, 4, 5, 6];
const newLength = arr.unshift(0, 1);
console.log(arr); // output: [0, 1, 2, 3, 4, 5, 6]
console.log(newLength); // output: 7
splice(): Removing, Replacing, or Adding Elements In Place
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. It returns an array containing the deleted elements. Warning: splice() modifies the original array.
Its parameters are (startIndex, deleteCount, item1, item2, ...)
.
// Use Case 1: Remove elements
const arrRemove = [1, 2, 3, 4, 5];
// Start at index 2, remove 2 elements
const removedItems = arrRemove.splice(2, 2);
console.log(removedItems); // output: [3, 4] (the removed elements)
console.log(arrRemove); // output: [1, 2, 5] (original array is modified)
// Use Case 2: Replace & Insert elements
const arrReplace = [1, 10, 23, 5];
// Start at index 1, remove 2 elements (10, 23), insert 2, 3, 4
const replacedItems = arrReplace.splice(1, 2, 2, 3, 4);
console.log(replacedItems); // output: [10, 23] (the removed elements)
console.log(arrReplace); // output: [1, 2, 3, 4, 5] (original array is modified)
slice(): Creating a Shallow Copy or Subset of an Array
The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included). The original array will not be modified.
const arr = [1, 2, 3, 4, 5];
// Get elements from index 2 to the end
const slicedArr1 = arr.slice(2);
console.log(slicedArr1); // output: [3, 4, 5]
// Get elements from index 2 up to (but not including) index 4
const slicedArr2 = arr.slice(2, 4);
console.log(slicedArr2); // output: [3, 4]
// Original array remains unchanged
console.log(arr); // output: [1, 2, 3, 4, 5]
concat(): Merging Two or More Arrays into a New Array
The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array containing the elements of the joined arrays.
const arr1 = [1, 2];
const arr2 = [3, 4, 5];
const arr3 = [6];
const combinedArr = arr1.concat(arr2, arr3);
console.log(combinedArr); // output: [1, 2, 3, 4, 5, 6]
// Original arrays remain unchanged
console.log(arr1); // output: [1, 2]
console.log(arr2); // output: [3, 4, 5]
flat(): Creating a New Array with Sub-Array Elements Concatenated
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. The default depth is 1. It does not modify the original array.
const nestedArr = [1, [2, 3], [4, [5, 6]]];
// Flatten one level deep (default)
const flattenedArr1 = nestedArr.flat();
console.log(flattenedArr1); // output: [1, 2, 3, 4, [5, 6]]
// Flatten two levels deep
const flattenedArr2 = nestedArr.flat(2);
console.log(flattenedArr2); // output: [1, 2, 3, 4, 5, 6]
// Original array remains unchanged
console.log(nestedArr); // output: [1, [2, 3], [4, [5, 6]]]
join(): Joining Array Elements into a String
The join() method creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
const arr = [1, 2, 3, 4, 5];
// Join with default comma separator
const joinedComma = arr.join();
console.log(joinedComma); // output: '1,2,3,4,5'
// Join with ' | ' separator
const joinedPipe = arr.join(' | ');
console.log(joinedPipe); // output: '1 | 2 | 3 | 4 | 5'
find: Finding the First Element That Passes a Test
The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined
is returned.
const arr = [1, 2, 3, 4, 5];
// Find the first number greater than 3
const firstGreaterThanThree = arr.find((num) => num > 3);
console.log(firstGreaterThanThree); // output: 4
// Find a number not present
const findSeven = arr.find((num) => num === 7);
console.log(findSeven); // output: undefined
indexOf(): Finding the First Index of a Specific Element
The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. You can optionally provide a second argument to specify the index from where the search should start.
const arr = ['a', 'b', 'c', 'd', 'c'];
// Find the index of 'c'
const indexC = arr.indexOf('c');
console.log(indexC); // output: 2 (finds the first occurrence)
// Find the index of 'c' starting from index 3
const indexCFrom3 = arr.indexOf('c', 3);
console.log(indexCFrom3); // output: 4
// Find the index of 'z' (not present)
const indexZ = arr.indexOf('z');
console.log(indexZ); // output: -1
toString(): Getting a String Representation of an Array
The toString() method returns a string representing the specified array and its elements. It joins the elements with a comma (,
) separator, similar to join() without arguments.
const arr = [1, 2, 'a', 'b'];
const stringArr = arr.toString();
console.log(stringArr); // output: '1,2,a,b'
fill(): Filling Array Elements With a Static Value In Place
The fill() method 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. Warning: fill() modifies the original array. Its parameters are (value, startIndex, endIndex)
.
const arr = [1, 2, 3, 4, 5];
// Fill with 0 from index 1 up to (but not including) index 3
arr.fill(0, 1, 3);
console.log(arr); // output: [1, 0, 0, 4, 5] (original array is modified)
// Fill the entire array with 9
arr.fill(9);
console.log(arr); // output: [9, 9, 9, 9, 9]
Mastering these 22 JavaScript array methods will significantly improve your coding efficiency and readability. Bookmark this page for future reference! For a structured approach to learning JavaScript basics, check out our Learn JavaScript in 4 Weeks: Beginners Guide.
Happy learning!