Iterating Arrays with forEach and map - JavaScript

 

JavaScript arrays are like a party—you invite elements, and then you want to interact with each one. But how do you efficiently greet every guest (element)? Meet forEach and map, the dynamic duo of JavaScript iteration! 

1. forEach() - The Friendly Tour Guide 

What is forEach()?

forEach() is like that friend who introduces you to everyone at a party. It loops through each element in an array and lets you perform an action on them.

Syntax:

array.forEach(function(element, index, array) {
  // Do something with element
});

Example:

let guests = ["Alice", "Bob", "Charlie"];
guests.forEach((guest, index) => {
  console.log(`Guest #${index + 1}: ${guest}`);
});

Output:

Guest #1: Alice
Guest #2: Bob
Guest #3: Charlie

When to Use forEach():

When you want to iterate over an array without modifying it. When you just want to execute a function for each element.

Does NOT return a new array! (Unlike map(), as we'll see next.)

2. map() - The Array Transformer 

What is map()?

map() is like a magical spell that transforms an array into a new one. It applies a function to every element and returns a shiny, brand-new array. 

Syntax:

let newArray = array.map(function(element, index, array) {
  return element * 2; // Example transformation
});

Example:

let numbers = [1, 2, 3, 4];
let doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers);

Output:

[2, 4, 6, 8]

When to Use map():

When you need a transformed version of an array.  When you want to keep the original array unchanged.

Returns a new array!

3. forEach() vs map() - Battle of the Iterators 

Feature forEach()  map() 
Returns a new array? No Yes
Modifies the original array? No No
Best for? Side effects (logging, updates) Transforming data

Quick Example:

let numbers = [1, 2, 3];

// Using forEach
numbers.forEach(num => console.log(num * 2));

// Using map
let doubled = numbers.map(num => num * 2);
console.log(doubled);

Key Takeaway:

  • Use forEach() when you want to do something with each element (like logging or modifying DOM).
  • Use map() when you want to transform each element into something new.

Conclusion 

Both forEach() and map() are amazing tools for iterating over arrays, but they serve different purposes. If you just want to loop through an array, forEach() is your go-to. If you need a new array with transformed values, map() is your best friend. 

Now go forth and iterate like a JavaScript ninja!

Post a Comment

0 Comments