Skip to main content

Array Methods

JavaScript Arrays come bundled with extremely powerful "Higher-Order" methods. A Higher-Order Method is simply a method that accepts a function as an argument (Callback).

1. forEach()

Iterates elegantly over an array instead of writing a clunky for loop.

const fruits = ["Apple", "Banana", "Cherry"];
fruits.forEach((fruit) => {
console.log(`Eating ${fruit}`);
});

2. map()

Returns a brand new array consisting of the results of running your callback on every element. Highly utilized in React!

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);

console.log(doubled); // [2, 4, 6]

3. filter()

Returns a new array containing ONLY elements that returned true inside your test callback.

const ages = [15, 20, 25, 12];
const adults = ages.filter(age => age >= 18);

console.log(adults); // [20, 25]

4. reduce()

Boils an entire array down to a single value. It accumulates data.

const prices = [10, 20, 30];
const total = prices.reduce((acc, curr) => acc + curr, 0);

console.log(total); // 60