for Loops in JavaScript

Many loops follow the pattern shown in the while examples. First a “counter” binding is created to track the progress of the loop. Then comes a while loop, usually with a test expression that checks whether the counter has reached its end value. At the end of the loop body, the counter is updated to track progress.

Because this pattern is so common, JavaScript and similar languages pro­vide a slightly shorter and more comprehensive form, the for loop.

for (let number = 0;

number <= 12;

number = number + 2) {

console.log(number);

}

// → 0

// → 2

// … etcetera

This program is exactly equivalent to the earlier even-number-printing example (page 30). The only change is that all the statements that are related to the “state” of the loop are grouped together after for.

The parentheses after a for keyword must contain two semicolons. The part before the first semicolon initializes the loop, usually by defining a bind­ing. The second part is the expression that checks whether the loop must continue. The final part updates the state of the loop after every iteration.

In most cases, this is shorter and clearer than a while construct.

This is the code that computes 210 using for instead of while:

let result = 1;

for (let counter = 0;

counter < 10;

counter = counter + 1) {

result = result * 2;

}

console.log(result);

// → 1024

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 *