Languages
[Edit]
EN

JavaScript - break statement

0 points
Created by:
Elmer-Li
516

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

1. In loops

In this example, we useĀ break statement inside a for loop to terminate the loop when theĀ iĀ iterator value reaches 3.

// ONLINE-RUNNER:browser;

for (let i = 0; i < 5; i++) {
    if (i === 3) {
        break;
    }
    console.log(i);
}

2. In switch statement

In this example, we useĀ break statement to terminateĀ the switch statement when a case is matched and its code executes.

// ONLINE-RUNNER:browser;

const number = 1;

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

3. In labeled blocks

In this example, we useĀ break statement with outer_block label to break out both inner_block and outer_block.

// ONLINE-RUNNER:browser;

outer_block: {
    inner_block: {
        console.log('inner block message 1');
        break outer_block;
        console.log('inner block message 2'); // will be skipped
    }
    console.log('outer block message 1'); // will be skipped
}

Ā 

See also

  1. JavaScript - loops: for, while, do while

  2. JavaScript - switch statement with example

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.
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