Break
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 40 of 77.
The break statement stops the loop instantly when it's encountered.
For example,
for (let i = 0; i < 10; i++) {
if (i == 6) {
break;
}
console.log(i);
}In the following example, the loop iterates regularly until it reaches number 6. Then the program enters the if statement and executes the break statement. This exits the loop immediately.
The output is:
0
1
2
3
4
5Challenge
BeginnerYou are given a code that prints the numbers from 1 to 20 (including).
Your task is to add if and break statements so that only the numbers from 1 to 8 will be printed, the loop will exit before printing the numbers from 9 to 20.
Cheat sheet
The break statement stops the loop instantly when it's encountered.
for (let i = 0; i < 10; i++) {
if (i == 6) {
break;
}
console.log(i);
}In this example, the loop exits when i equals 6, printing numbers 0 through 5.
Try it yourself
for (let i = 1; i <= 20; i++) {
console.log(i);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False