How to use break statement in Javascript

Description

The break statement breaks out of the loop, forcing execution to continue with the next statement after the loop.

Example


var num = 0; 
for (var i=1; i < 10; i++) { 
    if (i % 5 == 0) { /*from   w  ww  .j av  a  2s.c o m*/
        break; 
    } 
    num++; 
} 
console.log(num); //4 

The code above generates the following result.

Example 2

breaks to outer most loop


var num = 0; 
outermost: //  ww  w  .j a v  a2  s.  c  o  m
for (var i=0; i < 10; i++) { 
    for (var j=0; j < 10; j++) { 
        if (i == 5 && j == 5) {
            break outermost; 
        } 
        num++;
    } 
} 
console.log(num); //55 

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions