Iteration
suggest changeA traditional for-loop
A traditional for loop has three components:
- Initialization: runs once before the first iteration.
- Condition: evaluated before every iteration; the loop stops when it is false.
- Afterthought: runs after every iteration, typically to update a counter.
These three components are separated from each other by a ; symbol. Content for each of these three components is optional, which means that the following is the most minimal for loop possible:
for (;;) {
// Repeat until code in the loop uses break or return.
}
Because this loop has no condition, code in its body must eventually use break, return, or throw if it is not intended to run forever.
Usually, though, the initialization is used to declare an index, the condition is used to compare that index with a minimum or maximum value, and the afterthought is used to increment the index:
for (let i = 0; i < 10; i += 1) {
console.log(i);
}
Using a traditional for loop to loop through an array
An index-based loop is useful when the index itself is needed:
for (let i = 0; i < myArray.length; i += 1) {
console.log(myArray[i]);
}
Or, if you prefer to loop backwards, you do this:
for (let i = myArray.length - 1; i >= 0; i -= 1) {
console.log(myArray[i]);
}
Avoid putting assignments or several changing variables in a loop condition. A straightforward loop is easier to read and does not accidentally stop when an array element is a falsy value such as 0, false, or an empty string.
for (const value of myArray) {
console.log(value);
}
The equivalent while loop makes the counter update explicit:
let i = 0;
while (i < myArray.length) {
console.log(myArray[i]);
i += 1;
}
When both indices and values are needed, use entries():
for (const [index, value] of myArray.entries()) {
console.log(index, value);
}
Choose the form that communicates whether the code needs values, indices, or both.
These forms are available in current JavaScript runtimes.
A while loop
One alternative to a for loop is a while loop. To loop through an array, you could do this:
let index = 0;
while (index < myArray.length) {
console.log(myArray[index]);
index += 1;
}
The same iteration can be written as a for loop:
for (let index = 0; index < myArray.length; index += 1) {
console.log(myArray[index]);
}
for...in
Use for...in to visit an object's enumerable string keys:
for (const key in object) {
console.log(key, object[key]);
}
Do not use for...in for array values. It also visits inherited enumerable properties unless they are filtered. Prefer Object.keys(), Object.values(), or Object.entries() when only an object's own properties are wanted.
for...of
The for...of loop is the clearest way to iterate over an array's values when the loop may need break, continue, or await:
const myArray = [1, 2, 3, 4];
for (const value of myArray) {
const twoValue = value * 2;
console.log("2 * value is: %d", twoValue);
}
The following example shows the difference between a for...of loop and a for...in loop:
const myArray = [3, 5, 7];
myArray.foo = "hello";
for (const i in myArray) {
console.log(i); // logs 0, 1, 2, "foo"
}
for (const i of myArray) {
console.log(i); // logs 3, 5, 7
}
Array.prototype.keys()
The Array.prototype.keys() method can be used to iterate over indices like this:
const myArray = [1, 2, 3, 4];
for (const i of myArray.keys()) {
const twoValue = myArray[i] * 2;
console.log("2 * value is: %d", twoValue);
}
Array.prototype.forEach()
.forEach(...) dates from ES5 and is available in modern browsers, including Internet Explorer 9. The arrow function in the next example is newer than that.
[1, 2, 3, 4].forEach((value) => {
const twoValue = value * 2;
console.log("2 * value is: %d", twoValue);
});
forEach() cannot be stopped with break or continue, and it does not await an asynchronous callback. Use for...of when either behavior is needed.
In all versions of JavaScript, it is possible to iterate through the indices of an array using a traditional C-style for loop.
const myArray = [1, 2, 3, 4];
for (let i = 0; i < myArray.length; i += 1) {
const twoValue = myArray[i] * 2;
console.log("2 * value is: %d", twoValue);
}
It’s also possible to use while loop:
const myArray = [1, 2, 3, 4];
let i = 0;
let sum = 0;
while (i < myArray.length) {
sum += myArray[i];
i += 1;
}
console.log(sum);
Array.prototype.every
Array.prototype.every() tests elements until its callback returns a falsy value:
// [].every() stops once it finds a false result
// thus, this iteration will stop on value 7 (since 7 % 2 !== 0)
[2, 4, 7, 9].every((value) => {
console.log(value);
return value % 2 === 0; // iterate until an odd number is found
});
The equivalent loop is:
const arr = [2, 4, 7, 9];
for (let i = 0; i < arr.length; i += 1) {
console.log(arr[i]);
if (arr[i] % 2 !== 0) break;
}
Array.prototype.some
Array.prototype.some() tests elements until its callback returns a truthy value:
// some() stops after the callback returns true for 7.
[2, 4, 7, 9].some((value) => {
console.log(value);
return value === 7; // iterate until we find value 7
});
The loop has to log 7 and then stop. A condition that fails before the body skips that element:
const arr = [2, 4, 7, 9];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
if (arr[i] === 7) break;
}
Libraries
Finally, many utility libraries also have their own foreach variation. Three of the most popular ones are these:
jQuery.each(), in jQuery:
$.each(myArray, function(key, value) {
console.log(value);
});
_.each(), in Underscore.js:
_.each(myArray, function(value, key, myArray) {
console.log(value);
});
_.forEach(), in Lodash.js:
_.forEach(myArray, function(value, key) {
console.log(value);
});
See also the following question on SO, where much of this information was originally posted: