DEV Community

front_end_shifu_2022
front_end_shifu_2022

Posted on

loop skipping parts,break ,continue

for loop skipping part:
any part of for loop can be skipped

we can omit begin if we don’t need to do anything at the loop start.

Like here:
let i = 0; // we have i already declared and assigned
for (; i < 3; i++) { // no need for "begin"
alert( i ); // 0, 1, 2
}

We can also remove the step part:
let i = 0;
for (; i < 3;) {
alert( i++)
}

We can actually remove everything, creating an infinite loop:
for (;;) {
// repeats without limits
} );
}

Note
the two for semicolons ; must be present. Otherwise, there would be a syntax error.

Break
we can break loop any time using the special break directive.

e.g.

let sum = 0;
while (true) {
let value = +prompt("Enter a number", '');
if (!value) break; // (*)
sum += value;
}
alert( 'Sum: ' + sum );

In the above example if none of value is entered or cancled The break directive is activated at the line (*) . It stops the loop immediately, passing control to the first line after the loop. Namely, alert.

continue
The continue directive is a “lighter version” of break. It doesn’t stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).

We can use it if we’re done with the current iteration and would like to move on to the next one.

e.g.
loop uses continue to output only odd values:

for (let i = 0; i < 10; i++) {
// if true, skip the remaining part of the body
if (i % 2 == 0) continue;
alert(i); // 1, then 3, 5, 7, 9
}
For even values of i, the continue directive stops executing the body and passes control to the next iteration of for (with the next number). So the alert is only called for odd values.

Top comments (0)