Course Content
Introduction to JavaScript
4. Conditional Statements
Introduction to JavaScript
break
The break
keyword is a loop terminator, allowing you to exit a loop prematurely.
Example 1: Stopping an Infinite Loop
In this example, the break
keyword stops the infinite while
loop when i
becomes equal to 6
, after the i++
operation.
Example 2: Breaking a for
Loop
Here, the variable a
is incremented by i
during each iteration (0 + 1 + 2 + 3 + 4) until i
becomes equal to 4. At that point, the break
statement is triggered.
i = 0 | a = 0 + 0 |
i = 1 | a = 0 + 1 |
i = 2 | a = 1 + 2 |
i = 3 | a = 3 + 3 |
i = 4 | a = 6 + 4 , break |
Example 3: Breaking a while
Loop Immediately
In this example, the break
statement inside the while
loop immediately terminates the loop, preventing any code below it from executing within the same block.
Note
Remember that the
break
statement is a powerful tool for controlling the flow of your loops, allowing you to exit them when specific conditions are met.
Everything was clear?