Array iteration is a crucial concept in JavaScript, allowing developers to efficiently process and manipulate data stored in arrays. It provides powerful methods to loop through array elements, perform operations, and create new arrays based on specific conditions.
The forEach()
method executes a provided function once for each array element. It's ideal for performing side effects without creating a new array.
const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(fruit => console.log(fruit));
// Output:
// apple
// banana
// cherry
map()
creates a new array with the results of calling a provided function on every element in the array. It's perfect for transforming data.
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
Use filter()
to create a new array with all elements that pass the test implemented by the provided function.
const ages = [18, 21, 15, 35, 12];
const adults = ages.filter(age => age >= 18);
console.log(adults); // [18, 21, 35]
The reduce()
method executes a reducer function on each element of the array, resulting in a single output value. It's useful for accumulating or combining array elements.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15
filter()
followed by map()
).To deepen your understanding of JavaScript array iteration, explore these related topics:
Mastering array iteration methods is essential for efficient data manipulation in JavaScript. These techniques form the foundation for many advanced programming patterns and are widely used in modern web development.