JavaScript Array Methods
JavaScript arrays ship with a large library of built-in methods for transforming, searching, combining, and reshaping their contents.
Working with array methods
Array methods fall into two broad groups. Mutating methods change the original array in place, while non-mutating methods leave the original untouched and return a new array or value. Knowing which category a method belongs to helps you avoid bugs where data changes unexpectedly, especially in larger applications where the same array is shared between different parts of the code.
Some of the most useful methods are the higher-order methods map, filter, and reduce. They accept a callback function and apply it across the array, letting you express transformations declaratively instead of writing manual loops. Each of these returns a value without modifying the source array.
map, filter, and reduce
<!DOCTYPE html>
<html>
<body>
<h2>map, filter, and reduce</h2>
<script>
const numbers = [1, 2, 3, 4, 5];
// map: build a new array by transforming each element
const doubled = numbers.map((n) => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter: keep only elements that pass a test
const evens = numbers.filter((n) => n % 2 === 0);
console.log(evens); // [2, 4]
// reduce: collapse the array into a single value
const total = numbers.reduce((sum, n) => sum + n, 0);
console.log(total); // 15
</script>
</body>
</html>Searching, joining, and slicing
Beyond transformation, arrays offer methods to locate elements and to combine or extract portions. Use indexOf and includes for simple value checks, and find or findIndex when you need to match by a condition. To pull out a section without changing the original, use slice; to change the array in place by removing or inserting elements, use splice.
Finding and extracting elements
<!DOCTYPE html>
<html>
<body>
<h2>Finding and extracting elements</h2>
<script>
const words = ["sky", "tree", "river", "stone"];
console.log(words.includes("river")); // true
console.log(words.indexOf("tree")); // 1
// find returns the first element matching a condition
const longWord = words.find((w) => w.length > 4);
console.log(longWord); // "river"
// slice copies a section without mutating the original
const firstTwo = words.slice(0, 2);
console.log(firstTwo); // ["sky", "tree"]
console.log(words.length); // 4 (unchanged)
</script>
</body>
</html>- map returns a new array of the same length with transformed values.
- filter returns a new array containing only elements that pass a test.
- reduce boils an array down to a single accumulated result.
- slice copies part of an array; splice mutates the array in place.
- join turns an array into a string, and split turns a string back into an array.