Arrays are one of the most common data structures you'll work with. While for loops get the job done, modern JavaScript provides several powerful, built-in methods that make array manipulation much more elegant. These are "higher-order functions" because they take another function as an argument (a callback).

Let's look at three of the most essential ones. We'll use this array for our examples:

JavaScript


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

1. .map() - To Transform Data

The .map() method creates a new array by calling a provided function on every element in the original array. It's used when you want to transform each item in an array into something else.

Code Snippet: Doubling Numbers

JavaScript


const doubled = numbers.map(function(number) {
  return number * 2;
});
// Using an arrow function for conciseness
const doubledArrow = numbers.map(number => number * 2);

console.log(doubled);       // [2, 4, 6, 8, 10, 12]
console.log(doubledArrow);  // [2, 4, 6, 8, 10, 12]
console.log(numbers);       // [1, 2, 3, 4, 5, 6] (The original array is unchanged!)

2. .filter() - To Select Data

The .filter() method creates a new array with all elements that pass the test implemented by the provided function. It's used when you want to select a subset of items from an array.

Code Snippet: Getting Even Numbers

JavaScript


const evens = numbers.filter(function(number) {
  return number % 2 === 0; // The test: return true to keep the element
});
// Using an arrow function
const evensArrow = numbers.filter(number => number % 2 === 0);

console.log(evens);       // [2, 4, 6]
console.log(evensArrow);  // [2, 4, 6]
console.log(numbers);     // The original array is still unchanged

3. .reduce() - To Aggregate Data

The .reduce() method is the most versatile. It executes a "reducer" function on each element of the array, resulting in a single output value. It's used when you want to "boil down" an array to one value, like a sum, an average, or even a new object.

The reducer function takes two main arguments: an accumulator (the value being built up) and the current value from the array.

Code Snippet: Summing All Numbers

JavaScript


// reduce((accumulator, currentValue) => ..., initialValue)
const sum = numbers.reduce((total, number) => {
  return total + number;
}, 0); // 0 is the initial value of the accumulator ('total')

console.log(sum); // 21 (which is 1+2+3+4+5+6)

Chaining Methods You can chain these methods together to perform complex operations in a very readable way.

JavaScript


// Get the sum of the squares of all the odd numbers
const numbers2 = [1, 2, 3, 4, 5];

const result = numbers2
  .filter(n => n % 2 !== 0) // [1, 3, 5]
  .map(n => n * n)         // [1, 9, 25]
  .reduce((sum, n) => sum + n, 0); // 1 + 9 + 25 = 35

console.log(result); // 35