Which JavaScript Loop Wins? A Speed and Use‑Case Battle of for, forEach, map, for…in and for…of
This article compares five JavaScript iteration constructs—classic for, forEach, map, for...in and for...of—explaining their origins, semantics, performance characteristics, and appropriate use‑cases, while providing concrete code examples and guidance on breaking, continuing, and avoiding common pitfalls.
Introduction
The classic for loop is the fastest because it has no extra function calls or context, but in real development we must balance semantics, readability, and performance when choosing an iteration method.
Self‑Introduction of Each Method
for
Originating as the earliest loop statement, it satisfies most developer needs by iterating over an index.
forEach
Introduced in ES5, it executes a callback for each existing array element in ascending order, skipping deleted or uninitialized slots. It is essentially an enhanced for loop.
map
Also from ES5, map creates a new array by applying a callback to each element of the original array, leaving the source unchanged.
for...in
ES5 enumeration that iterates over an object's enumerable properties (including prototype properties) in arbitrary order; not recommended for arrays.
for...of
ES6 iteration over any iterable object (Array, Map, Set, String, TypedArray, arguments, etc.) using a custom iterator.
Code Examples
let arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
console.log(i);
console.log(arr[i]);
} let profile = {name: "April", nickname: "二十七刻", country: "China"};
for (let i = 0, keys = Object.keys(profile); i < keys.length; i++) {
console.log(keys[i]);
console.log(profile[keys[i]]);
} let str = "abcdef";
for (let i = 0; i < str.length; i++) {
console.log(i);
console.log(str[i]);
} let articleParagraphs = document.querySelectorAll('.article > p');
for (let i = 0; i < articleParagraphs.length; i++) {
articleParagraphs[i].classList.add('paragraph');
} arr.forEach(i => console.log(i)); let res = arr.map(i => i * i);
console.log(res); // [1,4,9,16,25] for (let i in profile) {
console.log(i);
console.log(profile[i]);
} for (let item of arr) {
console.log(item);
} let iterable = new Map([["a",1],["b",2],["c",3]]);
for (let entry of iterable) {
console.log(entry);
}Capability Identification
Choose the method that best fits the scenario: for for raw speed, for...of for iterables when you need early exit, forEach when you only need the value, map when you need a transformed array, and for...in for enumerating object properties.
Breaking and Continuing
Use break to exit the current loop and continue to skip to the next iteration. Neither forEach nor map support these statements because their callbacks are not loop bodies.
Notes on forEach and map
Both forEach and map cannot be broken out of; forEach returns undefined, making chaining impossible, while map returns a new array and can be chained with reduce, filter, etc.
Prototype Enumeration Pitfall
for...inalso enumerates properties added to prototypes. Use obj.hasOwnProperty(key) inside the loop to filter out inherited properties.
Performance Ranking
Empirical tests (not shown) yield the order: for > for...of > forEach > map > for...in. The ranking reflects call‑stack overhead, iterator creation, and type conversions.
Conclusion
In practice, combine semantics, readability, and performance: use map for array‑to‑array transformations, forEach or for...of for simple traversals, for...in for pure object enumeration, and reserve for for the most performance‑critical loops.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
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.
