Updating Bindings Succinctly in JavaScript

Having the looping condition produce false is not the only way a loop can finish. There is a special statement called break that has the effect of immedi- atelyjumping out of the enclosing loop.

This program illustrates the break statement. It finds the first number that is both greater than or equal to 20 and divisible by 7.

for (let current = 20; ;

current = current + 1) {

if (current % 7 == 0) {

console.log(current);

break;

}

}

// → 21

Using the remainder (%) operator is an easy way to test whether a num­ber is divisible by another number. If it is, the remainder of their division is zero.

The for construct in the example does not have a part that checks for the end of the loop. This means that the loop will never stop unless the break statement inside is executed.

If you were to remove that break statement or you accidentally write an end condition that always produces true, your program would get stuck in an infinite loop. A program stuck in an infinite loop will never finish running, which is usually a bad thing.

The continue keyword is similar to break, in that it influences the progress of a loop. When continue is encountered in a loop body, controljumps out of the body and continues with the loop’s next iteration.

Source: Haverbeke Marijn (2018), Eloquent JavaScript: A Modern Introduction to Programming,

No Starch Press; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *