Console Learner — An interactive JavaScript course.


2.6 Loops & Iteration

JavaScript supports four statements for looping (iteration):

for (init; test; update)
    statement
This for syntax is really only a short-form of the following while syntax:

init;
while (test) {
    statement
    update;
}
for (variable in object)
    statement
The variable expression must evaluate to a variable name or declaration. It is assigned to each of the object property names (in order).
for (variable of iterable)
    statement
The variable expression must evaluate to a variable name or declaration. This is similar to the for...in loop, but works for Array and other iterables (not covered here).
while (condition)
    statement
While the condition expression evaluates to true, the statement is executed. The loop terminates when condition evaluates to false.
do
    statement
while (condition)
The statement is executed for each pass through the loop. After each pass, the condition expression is evaluated. The loop terminates when condition evaluates to false.
>>>
var arr = ['a', 'b', 'c'],
    obj = { a: 1, b: 2, c: 3 };


  
>>>
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.
>>>
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 hidden (not enumerable).
>>>
for (var val of arr) {
    print(val);
}

  
The more compact way to iterate over an array is usually the for...of loop (added in ES6). It is less prone to mistakes, but wasn't available in all major browsers until 2015.
>>>
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.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.