In JavaScript, the break statement is used to terminate a loop or a switch statement. When encountered, it immediately exits the current loop or switch statement and resumes execution at the next statement following the loop or switch.
break in for loopsThe break statement can be used in a for loop to terminate it when a certain condition is met:
index.tsx104 chars8 lines
In the above example, the loop will terminate when i equals 5, and the output will be all numbers from 0 to 4.
break in while loopsSimilarly to a for loop, you can also use break in a while loop:
index.tsx108 chars10 lines
break in switch statementsThe break statement is also used to terminate a switch statement:
index.tsx251 chars14 lines
In this example, if color is "red", the output will be "You chose red.", and the switch statement will terminate. If color is neither "red", "green", nor "blue", the default case will execute.
gistlibby LogSnag