Looping
For
The most popular way of iterating in JavaScript is using the for
statement.
for (let i = 0; i < 10; i++) {
console.log(i)
} // 0,1,2,3,4,5,6,7,8,9 => undefined
For In
The for...in
statement is used to iterate in an arbitrary order over enumerable properties of an object keyed by strings only (therefore not by symbols).
const o = { a: 1, b: 2 }
for (const k in o) {
console.log(k)
console.log(o[k])
} // "a", 2, "b", 2 => undefined
For Of
The for...in
iterator iterates over property names but the for..of
iterator iterates over property values..
const o = { a: 1, b: 2 }
for (const v of o) {
console.log(v)
} // 1, 2 => undefined
While
The while
loop runs as long as a specified condition is of a truthy value.
let n = 0
while (n < 10) {
console.log(n)
n++
} // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 => 9
Do While
The do...while
statement repeats until a specified condition is falsy.
let n = 0
do {
console.log(n)
n++
} while (n < 10) // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 => 9
The difference of the do...while
loop to the while
loop is that the code block will run at least once with do...while
even when the provided condition is falsy.
Break
The break
statement can be used with for
iterators, loops and, as already noted, with switch
. Using the break
statement stops the relevant iteration or loop.
Continue
While the break
statement stops a given iteration or a loop as a whole the continue
statement omits only a given part of the iteration process and continues with the following parts.
Labeled Loops
JavaScript allows for labeled loops that identify them and make them referable in other parts of the code. The break
and continue
statements can be used with labeled loops to target them by their name. This can be used for example in nested loops.
let n = 0
myLoop: while (n < 3) {
console.log(n)
n++
}