There are many different kinds of loops, but they all essentially do the same thing: they repeat an action some number of times.
The statements for loops provided in JavaScript are:
- for statement
- do…while statement
- while statement
- labeled statement
- break statement
- continue statement
- for…in statement
- for…of statement
for statement
for
is used to iterate a known number of times. This is the reason why it’s common to use for
to iterate over arrays using their length
property or, in general, any other sequence.
Syntax:
statement;
The pair of parentheses following the for
keyword consists of three different configurations, each separated by a semicolon (;
):
initialization
— here any variables to be used in the loop are initialized to given values. Moreover, even variables can be declared, for example usingvar
.condition
— the condition that’s evaluated before every iteration. If it evaluates totrue
, the loop’s body is executed, or else execution moves out of the loop.update
— an expression that’s evaluated after every iteration. Typically this updates a variable’s value that’s used in the loop’s condition so that it eventually becomesfalse
at a certain point, and thus the loop comes to an end.
Ex:
1 2 3 4 5 6 7 8 9 10 11 | // Basic counting for (var i = 0; i <= 4; i++) { console.log(i); } /* Console 0 1 2 3 4 */ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // Iterating over an array var nums = [1, 10, 5, -9, -1]; for (var i = 0; i < nums.length; i++) { console.log(nums[i]); } /* Console 1 10 5 -9 -1 */ |
1 2 3 4 5 6 7 8 9 | // Getting numbers input var n = Number(prompt('How many numbers?')); var sum = 0; for (var i = 0; i < n; i++) { sum += Number(prompt('Enter number ' + (i + 1))); } document.write(sum); |
do…while statement
The do...while
statement repeats until a specified condition evaluates to false.
Syntax:
statement
while ( condition ) ;
statement
is always executed once before the condition is checked.- If
condition
istrue
, the statement executes again. At the end of every execution, the condition is checked. When the condition isfalse
, execution stops, and control passes to the statement followingdo...while
.
1 2 3 4 5 | let i = 0; do { i += 1; console.log(i); } while (i < 5); |
while statement
A while
statement executes its statements as long as a specified condition evaluates to true
.
Syntax:
statement
If thecondition
becomes false
, statement
within the loop stops executing and control passes to the statement following the loop.
Ex:
1 2 3 4 5 6 | let n = 0; let x = 0; while (n < 3) { n++; x += n; } |
labeled statement
A label
provides a statement with an identifier that lets you refer to it elsewhere in your program.
Syntax:
statement
label
may be any JavaScript identifier that is not a reserved word. The statement
that you identify with a label may be any statement.break statement
break
serves to break execution out of the loop that it is placed within.
break label;
- The first form of the syntax terminates the innermost enclosing loop or
switch
. - The second form of the syntax terminates the specified enclosing labeled statement.
Ex:
1 2 3 4 5 6 7 8 9 10 11 | for (var i = 0; i < 5; i++) { if (i === 2) { break; } console.log(i); } /* Console 0 1 */ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | let x = 0; let z = 0; labelCancelLoops: while (true) { console.log("Outer loops:", x); x += 1; z = 1; while (true) { console.log("Inner loops:", z); z += 1; if (z === 10 && x === 10) { break labelCancelLoops; } else if (z === 10) { break; } } } |
continue statement
continue
keyword serves to signal to the JavaScript to the engine to skip the current iteration and move to the next one.continue label;
- When you use
continue
without a label, it terminates the current iteration of the innermost enclosingwhile
,do-while
, orfor
statement and continues execution of the loop with the next iteration. In contrast to thebreak
statement,continue
does not terminate the execution of the loop entirely. In awhile
loop, it jumps back to the condition. In afor
loop, it jumps to theincrement-expression
. - When you use
continue
with a label, it applies to the looping statement identified with that label.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 | let i = 0; let n = 0; while (i < 5) { i++; if (i === 3) { continue; } n += i; console.log(n); } // Logs: // 1 3 7 12 |
for…in statement
The for...in
statement iterates a specified variable over all the enumerable properties of an object. For each distinct property, JavaScript executes the specified statements.
statement
Ex:
1 2 3 4 5 6 7 8 9 10 | function dumpProps(obj, objName) { let result = ""; for (const i in obj) { result += `${objName}.${i} = ${obj[i]}<br>`; } result += "<hr>"; return result; } //car.make = Ford //car.model = Mustang |
for…of statement
The for...of
statement creates a loop Iterating over iterable objects (including Array
, Map
, Set
, arguments
object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
statement
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 | const arr = [3, 5, 7]; arr.foo = "hello"; for (const i in arr) { console.log(i); } // "0" "1" "2" "foo" for (const i of arr) { console.log(i); } // Logs: 3 5 7 |
1 2 3 4 5 6 7 | const obj = { foo: 1, bar: 2 }; for (const [key, val] of Object.entries(obj)) { console.log(key, val); } // "foo" 1 // "bar" 2 |