Frontend Development 12 min read

Differences Between JavaScript for Loop and forEach: Syntax, Performance, and Usage

This article explains the fundamental differences between JavaScript's for loop and forEach method, covering their syntax, behavior, performance characteristics, iterator concepts, usage scenarios, and practical code examples for array traversal and manipulation.

Top Architect
Top Architect
Top Architect
Differences Between JavaScript for Loop and forEach: Syntax, Performance, and Usage

JavaScript provides several looping constructs such as for , for...in , for...of , and forEach . Although they appear similar, they differ in essence, syntax, and performance. This article examines these differences from multiple dimensions.

Essential Differences

The classic for loop has existed since the early days of JavaScript. forEach was introduced in ES5 as a method on iterable objects like Array , Set , and Map . While for is a control‑flow statement, forEach is an iterator that traverses an iterable.

Definitions

Traversal refers to visiting each element of a data structure once. Iteration is a special form of recursion provided by an iterator, typically accessing elements in order. Iterable objects implement the Symbol.iterator method, which returns an iterator object.

Iterators and Generators

Calling Symbol.iterator on an iterable creates an iterator with a .next() method that returns {value, done} . Generators produce such iterators automatically. Example:

let arr = [1, 2, 3, 4];
let iterator = arr[Symbol.iterator]();
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: 4, done: false}
console.log(iterator.next()); // {value: undefined, done: true}

The for...of loop internally uses this iterator protocol.

forEach Parameters

The callback signature is arr.forEach((self, index, arr) => {}, thisArg) , where self is the current element, index its position, arr the original array, and thisArg the bound this value.

let arr = [1, 2, 3, 4];
let person = {name: '技术直男星辰'};
arr.forEach(function(self, index, arr) {
  console.log(`当前元素为${self} 索引为${index}, 属于数组${arr}`);
  console.log(this.name += '真帅');
}, person);

Control Flow Differences

for loops support break , continue , and return to exit or skip iterations. forEach cannot be interrupted with these statements because it is an iterator; attempting to use them results in errors or no effect.

To simulate early termination in forEach , a try/catch pattern can be used:

try {
  var arr = [1, 2, 3, 4];
  arr.forEach(function(item) {
    if (item === 3) {
      throw new Error("LoopTerminates");
    }
    console.log(item);
  });
} catch (e) {
  if (e.message !== "LoopTerminates") throw e;
}

Performance Comparison

Benchmarks in Chrome 62 and Node.js v9.1.0 show the order: for > forEach > map . The for loop is fastest because it has no extra function calls. forEach incurs callback overhead, and map is slower still because it creates a new array.

Practical Recommendations

Use for when performance is critical or when you need fine‑grained control (e.g., early exit, custom start index). Use forEach for simple, side‑effect‑only traversals where readability matters. Avoid using map solely for iteration; reserve it for transformations that produce a new array.

Understanding iterables, iterators, and generators helps you choose the right looping construct and write more efficient JavaScript code.

PerformanceJavaScriptarrayIteratorforeachfor loop
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.