...

Web Technologies - JAVASCRIPT

Back to Course

Lesson Description


Lession - #237 Javascript Break


The break statement causes a loop to "jumps out."

The continue command "jumps over" one loop iteration.

The Break Statement

In a previous chapter of this lesson, you saw how to use the break statement. It was used to escape from a switch(>
statement.

You can also use the break command to exit a loop:

Example:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>break</b> statement.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10; i++>
{ if (i === 4>
{ break; } text += "The number is " + i + "<br>"; } document.getElementById("demo">
.innerHTML = text; </script> </body> </html>


Output:
Sorry cannot be displayed
Try it here

When the loop counter reaches 3, the break statement ends the loop ("breaks" the loop>
.

The Continue Statement

If a stated condition happens, the continue statement breaks one iteration (in the loop>
and continues with the following iteration in the loop.

The value of 3 is omitted in this example:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>continue</b> statement.</p>

<p>A loop which will skip the step where i = 4.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10; i++>
{ if (i === 4>
{ continue; } text += "The number is " + i + "<br>"; } document.getElementById("demo">
.innerHTML = text; </script> </body> </html>


Output:
Sorry cannot be displayed
Try it here


Labels in JavaScript

To label JavaScript statements, use a label name and a colon before the statements:

label:
statements


The only JavaScript statements that can "jump out of" a code block are the break and continue statements.

Syntax:
break labelname;
continue labelname;


Only one loop iteration can be skipped with the continue statement (with or without a label reference>
.

Without a label reference, the break statement can only be used to exit a loop or a switch.

The break statement can be used to exit any code block using a label reference:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript break</h2>

<p id="cars"></p>

<script>
const car = ["BMW", "Volvo", "Saab", "Ford"];
let text = "";

list: {
  text += car[0] + "<br>"; 
  text += car[2] + "<br>"; 
  break list;
  text += car[1] + "<br>"; 
  text += car[3] + "<br>"; 
}

document.getElementById("cars">
.innerHTML = text; </script> </body> </html>


Output:
Sorry cannot be displayed
Try it here