javascript interactive

JavaScript Interactive — a console crash course


2.3 Loops & Iteration

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.

JavaScript supports four statements for looping (iteration):

  • for – Used for stepping though array indices (and similar).
  • for...in – Used for iterating object properties.
  • while – Used for generic iteration and event loops.
  • do...while – Used when the loop must be run though at least once.
>>>
var arr = ['a', 'b', 'c'];


  
>>>
for (var i = 0; i < arr.length; i++) {
    print(i + ': ' + arr[i]);
}

  
Looping over the entries in an array is achieved by stepping a variable from zero to the last index.
>>>
var obj = { a: 1, b: 2, c: 3 };


  
>>>
for (var key in obj) {
    print(key + ': ' + obj[key]);
}

  
Looping over the properties in an object is similar, but uses a slightly different syntax.
>>>
for (var key in arr) {
    print(key);
}

  
Since arrays are also objects, the array indices can be iterated as properties. Note that they are returned as strings when handled this way. And the length property is not iterable.
>>>
while (true) {
    print('stopping the loop...');
    break;
}

  
The break and continue statements are used to stop or proceed to the next step in a loop.
>>>

Index 1 2 3 4 5 6 7 8