A fundamental skill in programming is controlling how a program executes. The control of program execution is categorized using three control structures. They are "sequential", "selection", and "repetition". So far, you've written straightforward code that uses sequential JavaScript statements that execute one after another. More complex decision-making programs use selection and repetition. Programs also implement different types of looping structures, such as looping until some condition is met (sentinel) or looping a specific number of times (counter control). As you read through this section, you should notice that control structures in JavaScript use "reserved keywords" (if, else, switch).
For loops
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 provide 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. 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 binding. 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