Javascript - Statement break statement

Introduction

The break statement exits the loop immediately and continues with the next statement after the loop.

Here's an example:

Demo

var num = 0;

for (var i=1; i < 10; i++) {
    if (i % 5 == 0) {
        break;//from ww w .  j  a  v  a 2 s .  c om
    }
    num++;
}

console.log(num);    //4

Result

The num variable starts out at 0 and indicates the number of times the loop has been executed.

In this code, the for loop increments the variable i from 1 to 10.

In the body of loop, an if statement checks to see if the value of i is evenly divisible by 5 using the modulus operator.

If so, the break statement is executed and the loop is exited.

After the break statement has been hit, the next line of code to be executed is the console.log, which displays 4.

The break statement causes the loop to be exited before num can be incremented.

Related Topics

Exercise