Comparing JavaScript Looping Methods: for, forEach, map, for...in, and for...of
This article compares JavaScript's five main iteration constructs—for, forEach, map, for...in, and for...of—examining their syntax, use‑cases, performance characteristics, and how they handle break/continue, helping developers choose the most suitable method for a given scenario.
Several iteration methods in JavaScript are compared, focusing on performance, readability, and semantics.
for is the classic loop with no extra function calls; forEach and map were introduced in ES5, while for...in enumerates object properties and for...of iterates any iterable introduced in ES6.
Code examples demonstrate how each construct works on arrays, objects, strings, DOM nodes, arguments objects, and typed arrays.
let arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
console.log(i); // index
console.log(arr[i]); // element
}
arr.forEach(i => console.log(i)); // 1 2 3
let res = arr.map(i => i * i); // [1,4,9]
for (const item of arr) {
console.log(item); // 1 2 3
}
let obj = { a: 1, b: 2 };
for (const key in obj) {
console.log(key, obj[key]); // a 1, b 2
}The article discusses when to use each method, how break and continue behave, why forEach and map cannot be broken out of, and the impact of prototype properties on for...in .
Performance ranking (from fastest to slowest) is reported as: for > for...of > forEach > map > for...in , with explanations of underlying overhead.
In conclusion, developers should choose the loop that best balances semantics, readability, and performance for the specific scenario.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.