Iteration

Download javascript eBook

Example

A traditional for-loop

A traditional for loop has three components:

  1. The initialization: executed before the look block is executed the first time
  2. The condition: checks a condition every time before the loop block is executed, and quits the loop if false
  3. The afterthought: performed every time after the loop block is executed

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 (;;) {
    // Do stuff
}

Of course, you will need to include an if(condition === true) { break; } or an if(condition === true) { return; } somewhere inside that for-loop to get it to stop running.

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 (var i = 0, length = 10; i < length; i++) {
    console.log(i);
}

Using a traditional for loop to loop through an array

The traditional way to loop through an array, is this:

for (var i = 0, length = myArray.length; i < length; i++) {
    console.log(myArray[i]);
}

Or, if you prefer to loop backwards, you do this:

for (var i = myArray.length - 1; i > -1; i--) {
    console.log(myArray[i]);
}

There are, however, many variations possible, like for example this one:

for (var key = 0, value = myArray[key], length = myArray.length; key < length; value = myArray[++key]) {
    console.log(value);
}

... or this one ...

var i = 0, length = myArray.length;
for (; i < length;) {
    console.log(myArray[i]);
    i++;
}

... or this one:

var key = 0, value;
for (; value = myArray[key++];){
    console.log(value);
}

Whichever works best is largely a matter of both personal taste and the specific use case you're implementing.

Note that each of these variations is supported by all browsers, including very very old ones!


A while loop

One alternative to a for loop is a while loop. To loop through an array, you could do this:

var key = 0;
while(value = myArray[key++]){
    console.log(value);
}

Like traditional for loops, while loops are supported by even the oldest of browsers.

Also, note that every while loop can be rewritten as a for loop. For example, the while loop hereabove behaves the exact same way as this for-loop:

for(var key = 0; value = myArray[key++];){
    console.log(value);
}

for...in

In JavaScript, you can also do this:

for (i in myArray) {
    console.log(myArray[i]);
}

This should be used with care, however, as it doesn't behave the same as a traditional for loop in all cases, and there are potential side-effects that need to be considered. See Why is using "for...in" with array iteration a bad idea? for more details.

for...of

In ES 6, the for-of loop is the recommended way of iterating over a the values of an array:

6
let myArray = [1, 2, 3, 4];
for (let value of myArray) {
  let 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:

6
let myArray = [3, 5, 7];
myArray.foo = "hello";

for (var i in myArray) {
  console.log(i); // logs 0, 1, 2, "foo"
}

for (var 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:

6
let myArray = [1, 2, 3, 4];
for (let i of myArray.keys()) {
  let twoValue = myArray[i] * 2;
  console.log("2 * value is: %d", twoValue);
}

Array.prototype.forEach()

The .forEach(...) method is an option in ES 5 and above. It is supported by all modern browsers, as well as Internet Explorer 9 and later.

5
[1, 2, 3, 4].forEach(function(value, index, arr) {
  var twoValue = value * 2;
  console.log("2 * value is: %d", twoValue);
});

Comparing with the traditional for loop, we can't jump out of the loop in .forEach(). In this case, use the for loop, or use partial iteration presented below.

In all versions of JavaScript, it is possible to iterate through the indices of an array using a traditional C-style for loop.

var myArray = [1, 2, 3, 4];
for(var i = 0; i < myArray.length; ++i) {
  var twoValue = myArray[i] * 2;
  console.log("2 * value is: %d", twoValue);
}

It's also possible to use while loop:

var myArray = [1, 2, 3, 4],
    i = 0, sum = 0;
while(i++ < myArray.length) {
  sum += i;
}
console.log(sum);

Array.prototype.every

Since ES5, if you want to iterate over a portion of an array, you can use Array.prototype.every, which iterates until we return false:

5
// [].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(function(value, index, arr) {
  console.log(value);
  return value % 2 === 0; // iterate until an odd number is found
}); 

Equivalent in any JavaScript version:

var arr = [2, 4, 7, 9];
for (var i = 0; i < arr.length && (arr[i] % 2 !== 0); i++) { // iterate until an odd number is found
  console.log(arr[i]);
}

Array.prototype.some

Array.prototype.some iterates until we return true:

5
// [].some stops once it finds a false result
// thus, this iteration will stop on value 7 (since 7 % 2 !== 0)
[2, 4, 7, 9].some(function(value, index, arr) {
  console.log(value);
  return value === 7; // iterate until we find value 7
}); 

Equivalent in any JavaScript version:

var arr = [2, 4, 7, 9];
for (var i = 0; i < arr.length && arr[i] !== 7; i++) {
  console.log(arr[i]);
}

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:

Stats

Contributors: 11
2017-07-21
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook