Understanding loops
There are many ways to create loops in JavaScript, but the most common are the for
and while
statements and variations of them that are specific to arrays and objects. Also, functions in JavaScript can be used to create loops when using recursion. In this section, we will look at only the for
, while
, and do...while
statements.
while
The while
statement creates a loop that executes a block of code as long as the condition is true. The condition is evaluated before executing the block of code:
let i = 1; while (i <= 10) { console.log(i); i++; };
do...while
The do...while
statement creates a loop that executes a block of code at least once even if the condition is not met, and then repeats the loop as long as the condition is true. The condition is evaluated after executing the block of code:
let i = 0; do { console.log(`i value: ${i}`); i++; } while...