Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Understanding `for`, `forEach`, and `map` in JavaScript

1 min read .
Understanding `for`, `forEach`, and `map` in JavaScript

JavaScript offers several ways to iterate over arrays. for, forEach, and map overlap in what they can express, but each communicates a different intent.

Traditional for

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

Use a for loop when you need explicit index control, break, continue, unusual step sizes, or tight control over the iteration process.

forEach

numbers.forEach((number, index) => {
  console.log(index, number);
});

forEach is appropriate for side effects such as logging, updating the DOM, or calling another function for each item. It returns undefined and cannot be stopped early with break.

map

const doubled = numbers.map((number) => number * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

Use map when every input element should produce a corresponding value in a new array.

A Useful Rule

  • Use for when control flow is the priority.
  • Use forEach for side effects on every item.
  • Use map for transformations that produce a new array.

Do not choose solely from microbenchmarks. In most application code, expressing intent clearly matters more than small engine-specific performance differences.

Conclusion

These iteration tools are not competitors so much as different vocabulary. Choosing the one that matches your intent makes JavaScript code easier to read and maintain.

Related Posts

chevron-up