Languages
[Edit]
EN

JavaScript - break statement

0 points
Created by:
Wiktor-Sribiew
800

In this article, we would like to show you break statement in JavaScript.

Syntax

break [label];

Description

The break statement ends the current loop, switch, or label statement and proceeds to the statement following the ended statement.

Practical examples

Example 1 - while loop

In this example, we use break statement to terminate the while loop on the specific condition.

// ONLINE-RUNNER:browser;

let i = 0;

while (i < 5) {
  if (i === 2) {
    break;
  }
  i = i + 1;
}

console.log(i); // 2

Note:

If the statement we want to break is not a loop or switch, label is required.

Example 2 - switch

In this example, we use the break statement to terminate the switch statement when a case is matched and the corresponding code has been executed.

// ONLINE-RUNNER:browser;

const number = 2;

switch (number) {
  case 1:
    console.log('case 1 message...');
    break;
  case 2:
    console.log('case 2 message...');
    break;
  default:
    console.log('default message...');
    break;
}

References

  1. break - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Statements & declarations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join