JavaScript > Objects and Arrays > Array Basics > Array iteration (forEach, map, filter, reduce)
Array Iteration in JavaScript: forEach, map, filter, reduce
This snippet demonstrates the fundamental array iteration methods in JavaScript: forEach
, map
, filter
, and reduce
. Each method provides a different way to process array elements, offering flexibility for various tasks.
Introduction to Array Iteration
JavaScript provides several built-in methods for iterating over arrays. These methods allow you to perform operations on each element of an array without needing to write verbose loops. The most common are forEach
, map
, filter
, and reduce
. Each serves a specific purpose, making array manipulation more concise and readable.
forEach: Executing a Function for Each Element
The forEach
method executes a provided function once for each array element. It doesn't create a new array or modify the original one; it simply iterates and performs an action. The function passed to forEach
typically takes three arguments: the current element, the index of the current element, and the array itself. In this example, we iterate through an array of numbers and print each number multiplied by 2 to the console.
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number * 2);
});
map: Creating a New Array with Transformed Elements
The map
method creates a new array by applying a provided function to each element of the original array. The function transforms each element, and the transformed values are added to the new array. The original array remains unchanged. Here, we create a new array called doubledNumbers
, where each element is the original number multiplied by 2.
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(number) {
return number * 2;
});
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
filter: Creating a New Array with Filtered Elements
The filter
method creates a new array containing only the elements from the original array that pass a certain condition. The condition is defined by a function that returns true
for elements to be included in the new array and false
for elements to be excluded. In this case, we create a new array called evenNumbers
containing only the even numbers from the original array.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(function(number) {
return number % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4]
reduce: Accumulating Values into a Single Result
The reduce
method applies a function against an accumulator and each element of the array (from left to right) to reduce it to a single value. The function takes two arguments: the accumulator (which initially holds the initial value or the result of the previous call) and the current element. The initial value is passed as the second argument to reduce
. In this example, we calculate the sum of all numbers in the array. The accumulator starts at 0, and in each iteration, it's incremented by the current number.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
Concepts Behind the Snippet
The core concept is functional programming applied to array manipulation. These methods enable you to process data in a declarative way, focusing on what you want to achieve rather than how to achieve it using explicit loops. They promote code readability and maintainability.
Real-Life Use Case Section
Imagine you're processing a list of e-commerce products. map
could transform product prices by applying a discount. filter
could select products within a specific price range. reduce
could calculate the total value of all products in a shopping cart. forEach
can trigger an analytics event for each viewed product.
Best Practices
map
and filter
that create new arrays, leaving the original array unchanged. This prevents unexpected side effects.
Interview Tip
Be prepared to explain the differences between forEach
, map
, filter
, and reduce
. Understand their use cases and potential side effects. Demonstrate your ability to use them to solve common array manipulation problems.
When to use them
Memory Footprint
map
, filter
, and reduce
create new arrays, which can increase memory usage, especially for large arrays. forEach
does not create a new array and has a smaller memory footprint. Consider memory constraints when choosing an iteration method.
Alternatives
Traditional for
loops and while
loops are alternatives, but they are often more verbose and less readable than the array iteration methods. Libraries like Lodash offer similar and sometimes more performant alternatives, but using the built-in methods is generally preferred for simplicity.
Pros
Cons
map
, filter
, and reduce
create new arrays, potentially increasing memory usage.
FAQ
-
What is the main difference between
forEach
andmap
?
forEach
executes a function for each element in the array but doesn't return a new array.map
executes a function for each element and returns a new array containing the results of applying the function to each element. -
Can I use
async/await
inside aforEach
loop?
Be cautious.forEach
doesn't wait for the asynchronous operations to complete before moving to the next iteration. Use afor...of
loop orPromise.all
withmap
for proper asynchronous handling. -
How do I stop or break out of a
forEach
loop?
You cannot directly stop or break out of aforEach
loop. You'll need to use a traditionalfor
loop orfor...of
loop if you need that functionality.