What is Control Flow?
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).
Breaking Out of a Loop
false
is not the only way a loop can finish. There is a special statement called break
that has the effect of immediately jumping 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 number 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.
If you create an infinite loop in one of the examples on these pages, you'll usually be asked whether you want to stop the script after a few seconds. If that fails, you will have to close the tab that you're working in, or on some browsers close your whole browser, to recover.
The continue
keyword is similar to break
, in that it influences the progress of a loop. When
continue
is encountered in a loop body, control jumps out of the body and continues with the loop's next iteration.