JavaScript Array Iteration
JavaScript provides several methods for iterating over the elements of an array. These methods allow you to perform operations on each element of the array or filter elements based on certain conditions.
1. forEach()
Executes a provided function once for each array element.
Example:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => console.log(num)); // Output: 1 2 3 4 5
2. map()
Creates a new array populated with the results of calling a provided function on every element in the array.
Example:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
3. filter()
Creates a new array with all elements that pass the test implemented by the provided function.
Example:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
4. reduce()
Executes a reducer function on each element of the array, resulting in a single output value.
Example:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 15
These array iteration methods provide efficient ways to perform operations on array elements and transform arrays according to specific requirements.