break and continue
- Node.js course
- Beginner
- Lesson 46/116
- 4 min
Learn to exit a loop with break and skip with continue.
Exiting with break
To exit a loop early you use break. When break is called the loop ends immediately; the program continues with the statement after the loop. Even if the condition still holds, the loop does not run.
For example for (let i = 1; i <= 10; i++) { if (i === 5) { break; } console.log(i); } prints 1, 2, 3, 4 and stops at 5. break is especially useful in search tasks to end the loop once a match is found; it avoids needless iterations.
Skipping with continue
To skip the rest of an iteration and move to the next you use continue. break ends the loop, continue skips only that iteration. The loop keeps running as long as the condition stays true.
For example for (let i = 1; i <= 5; i++) { if (i % 2 === 0) { continue; } console.log(i); } prints only odd numbers: 1, 3, 5. continue is handy when you want to skip work under certain conditions; it often appears with an if clause.
Practice Stop at 5
Write a for loop: counter i starts at 1, condition i <= 10, step i++. In the body exit at 5 with if (i === 5) { break; }; then call console.log(i). The output must be four lines: 1, 2, 3, 4.
Starter code
// Write the for loop and break hereSample solution
for (let i = 1; i <= 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}Expected output
1 2 3 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write break
for (let i = 1; i <= 5; i++) {
if (i === 3) {
____;
}
console.log(i);
}
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break;
}
console.log(i);
}
Explanation: break exits the loop at once.
2 What does continue do?
for (let i = 1; i <= 3; i++) {
if (i === 2) { continue; }
console.log(i);
}- Ends the loop
- Skips to next iteration Correct answer
- Throws an error
- Restarts the loop
Explanation: continue skips the rest of the body and goes to the next iteration.
3 Match each command to its job
| Term | Meaning |
|---|---|
break |
Exits the loop |
continue |
Skips iteration |
if |
Tests a condition |
for |
Counted loop |