DEV Community

front_end_shifu_2022
front_end_shifu_2022

Posted on

loops

Loops are a way to repeat the same code multiple times.
while loop
syntax:
while (condition) {
// code
// so-called "loop body"
}
when the condition is true ,while loop can be executed.

let z = 0;
*while (z < 4) {
alert( z );
z++;
}
in the above example it will show 0 then 1 the 2 then 3 and z<4 which is false so the loop will stop. *

A single execution of the loop body is called an iteration.
if z++ were missing then the loop would execute infinite times.
Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated and converted to a boolean by while.

For instance, a shorter way to write while (i != 0) is while (i):

let i = 3;
while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops
alert( i );
i--;
}

The “do…while” loop
syntax:
do {
// loop body
} while (condition);

The loop will first execute the body, then check the condition, and, while it’s truthy, execute it again and again.
e.g.
let z = 0;
do {
alert( z );
z++;
} while (z<3);

This form of syntax should only be used when you want the body of the loop to execute at least once regardless of the condition being truthy.

for loop
syntax:
for (begin; condition; step) {
// ... loop body ...
}
it's complex and most commonly used loop.
It begin executes once, and then it iterates: after each condition test, body and step are executed.

// for (let z = 0; z < 2; z++) alert(i)

// run begin
let z = 0
// if condition → run body and run step
if (z < 2) { alert(z); z++ }
// if condition → run body and run step
if (z < 2) { alert(z); z++ }
// ...finish, because now z == 2

Inline variable declaration
if variable in declared in loop is called inline loop

for (let i = 0; i < 3; i++) {
alert(i); // 0, 1, 2
}
alert(i); // error, no such variable

Top comments (0)