What are the fastest ways to loop over an array with forEach or for...of in JavaScript? | A1Lab@FahadM to JavaScriptEnglish •
edit-2
12 days ago

What are the fastest ways to loop over an array with forEach or for...of in JavaScript?

message-square
0

A classic indexed **for loop** (with cached length) is the raw fastest loop in V8, while **for…of** offers nearly identical speed with cleaner syntax and supports break, continue, and async/await`.

Comparing for...of vs. .forEach()

const items = ["React", "Node", "TypeScript"];

// 1. for...of (Recommended: fast, supports break/continue & await)
for (const item of items) {
  if (item === "Node") break;
  console.log(item);
}

// 2. .forEach() (Callback overhead; cannot break early or await properly)
items.forEach((item, index) => {
  console.log(index, item);
});

Key Performance Rules

Use for...of: Whenever you need await inside a loop or early exit with break.

Use classic for (let i = 0, len = arr.length; i < len; i++): Inside performance-critical tight loops processing millions of elements.'