JS For Loops
JavascriptClassic for loop
Use when you need an index or want to control the start/end/step:
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Prints 0,1,2,3,4
for...of loop
Iterates over values of an iterable (arrays, strings, etc):
let arr = ["a", "b", "c"];
for (let value of arr) {
console.log(value);
}
// Prints "a", "b", "c"
for...in loop
Iterates over enumerable property names (keys) of an object or array:
let obj = {x:1, y:2};
for (let key in obj) {
console.log(key, obj[key]);
}
// Prints "x 1", "y 2"
Note: For arrays, for...in gives the index as a string.
for...in with Arrays
While for...in can be used with arrays, it is generally not recommended:
let arr = ["a", "b", "c"];
for (let i in arr) {
console.log(i, arr[i]);
}
// Prints "0 a", "1 b", "2 c"
However, for...in iterates over all enumerable properties, including custom properties and inherited ones. This can lead to unexpected results:
arr.extra = "oops";
for (let i in arr) {
console.log(i, arr[i]);
}
// Prints "0 a", "1 b", "2 c", "extra oops"
For arrays, prefer for or for...of loops.
Summary Table
| Loop | Use for |
|---|---|
for (init; cond; inc) | Indexes, counting, custom steps |
for (let v of arr) | Array/iterable values |
for (let k in obj) | Object keys/properties |