测验题

What is the purpose of the `break` and `continue` statements?

Topics
JAVASCRIPT
在GitHub上编辑

TL;DR

The break statement is used to exit a loop or switch statement prematurely, while the continue statement skips the current iteration of a loop and proceeds to the next iteration. For example, in a for loop, break will stop the loop entirely, and continue will skip to the next iteration.

for (let i = 0; i < 10; i++) {
if (i === 5) break; // exits the loop when i is 5
console.log(i);
}
for (let i = 0; i < 10; i++) {
if (i === 5) continue; // skips the iteration when i is 5
console.log(i);
}

Purpose of the break and continue statements

break statement

The break statement is used to exit a loop or a switch statement before it has completed all its iterations or cases. This is useful when you want to stop the execution of the loop or switch based on a certain condition.

Example in a loop

for (let i = 0; i < 10; i++) {
if (i === 5) break; // exits the loop when i is 5
console.log(i);
}
// Output: 0 1 2 3 4

Example in a switch statement

switch (day) {
case 1:
console.log('Monday');
break;
case 2:
console.log('Tuesday');
break;
// other cases
default:
console.log('Invalid day');
}

continue statement

The continue statement is used to skip the current iteration of a loop and proceed to the next iteration. This is useful when you want to skip certain iterations based on a condition without exiting the loop entirely.

Example in a loop

for (let i = 0; i < 10; i++) {
if (i === 5) continue; // skips the iteration when i is 5
console.log(i);
}
// Output: 0 1 2 3 4 6 7 8 9

Differences between break and continue

  • The break statement exits the loop or switch statement entirely.
  • The continue statement skips the current iteration and moves to the next iteration of the loop.

Further reading

在GitHub上编辑