JavaScript break Statement Tutorial

In this section, we will learn what the break statement is and how to use it in JavaScript.

What is break Statement in JavaScript?

The `break` statement is used in JavaScript to break the execution (iteration) of a loop.

When the `break` statement is used in a loop, it will break that loop (jumps out) and the execution engine will continue to execute the instructions after the loop.

Note: other than loops, we use the `break` keyword in the `switch` statement as well, which has the same effect (breaking the switch statement and the execution engine runs those instructions that come afterwards).

JavaScript break Statement Syntax:

break;

This operator does not take any argument.

Example: using the break statement in JavaScript for loop

const arr = [];
for (let i = 0; i<10; i++){
    if(i>5){
        break;
    }
    arr.push(i);
}
console.log(arr);
console.log("Done!");

Output:

[0, 1, 2, 3, 4, 5]

Done!

Here, the `for` loop supposed to loop through 10 elements. But because there’s a `break` statement that will be triggered (in the `if` statement) after the value of the `i` variable becomes 6, the loop breaks at this point and the instructions after the loop runs.

Example: using break statement in JavaScript while loop

var num = 0; 
while (num<100){
  if( num==30){
    break;
  }
  num++;
}
console.log(num);

Output:

30

Example: using break statement in JavaScript do while loop

var num = 0; 
do {
  if( num==30){
    break;
  }
  num++;
}
while (num<100)
console.log(num);

Example: using break statement in JavaScript switch case

var num = 0; 
switch (num){
  case 10: 
    console.log("The value is 10");
    break;
  case 20:
    console.log("The value is 20"); 
    break;
  case 0: 
    console.log("The value is 0");
    break; 
  default: 
    console.log("The value is unknown");
}
console.log("End");

Output:

The value is 0

End

Example: JavaScript foreach break (for of loop)

var name = "My name is Omid"; 
for (const character of name){
  if (character == "O"){
    console.log(character);
  }
}
console.log("End");

Output:

O

End

JavaScript Nested for Loop and break Statement

When using the break statement in a nested loop, it will only break the inner most loop! Basically, the parent loop will still move to the next iteration (if any).

So remember, when using the break statement in a nested loop, only the innermost loop will break.

Example: break and nested for loop in JavaScript

const array = [
  [1,2,3,4,5],
  [6,7,8,9,10]
];
for (const arr of array){
  for (const element of arr){
    if (element ==3){
      break;
    }
    console.log(element);
  }
}
console.log("End");

Output:

1 
2 
6 
7 
8 
9 
End

More to Read:

JavaScript continue statement tutorial

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies