JavaScript supports four statements for looping (iteration):
for (init; test; update) statementThis
for
syntax is really only a short-form of the
following while
syntax:init; while (test) { statement update; }
for (variable in object) statementThe 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) statementThe 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) statementWhile 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]); }
for (var key in obj) { print(key + ': ' + obj[key]); }
for (var key in arr) { print(key); }
for (var val of arr) { print(val); }
while (true) { print('stopping the loop...'); break; }
The console allows you to interact with the course material and examples. Use the following keys:
A special logging function is also available: