Line At A Time
Lesson 21: Break
Break Escape from a loop with break.
1let count = 0;
2while (true) {
3 console.log(count);
4 count++;
5 if (count === 5) {
6 break;
7 }
8}
Terminal
$ node main.js
0
1
2
3
4
Every line, explained
let count = 0;
let creates a variable whose value you PLAN to change later. The modern rule of thumb: use const unless you know the value will change; then use let. (You may see var in old code; it went out of style years ago.)
while (true) {
A while loop repeats its block for as long as the condition in the brackets is true. The condition is checked again before every trip around the loop. while (true) would repeat forever, because the condition is always true! We will need break to escape.
console.log(count);
console.log(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. console is the terminal itself, log is the tool that writes to it, joined with a dot.
count++;
count++ adds 1 to count, a short way of writing count = count + 1.
if (count === 5) {
if checks the condition inside its round brackets. If the condition is true, JavaScript runs the code between { and }; if it is false, it skips that code completely. Once the counter reaches 5, it is time to stop.
break;
break immediately stops the loop it is inside; JavaScript jumps to the first line after the loop's closing brace.
}
This } closes the if block.
}
This } closes the while loop.