Javascript – break – continue

The break statement “jumps out” of a loop.
Without label reference can only be used inside a loop or a switch.
With label reference it can be used to “jump out of” any JavaScript code block.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to do a loop with a break.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x="",i=0;
for (i=0;i<10;i++)
  {
  if (i==3)
    {
    break; // without label reference
    }
  x=x + "The number is " + i + "<br>";
  }
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

Notice:

if (i==3)
    {
    break;
    }

The result is:

The number is 0
The number is 1
The number is 2

break with label reference:

<!DOCTYPE html>
<html>
<body>

<script>
cars=["BMW","Volvo","Saab","Ford"];
list:
{
document.write(cars[0] + "<br>"); 
document.write(cars[1] + "<br>"); 
document.write(cars[2] + "<br>"); 
break list;
document.write(cars[3] + "<br>"); 
document.write(cars[4] + "<br>"); 
document.write(cars[5] + "<br>"); 
}
</script>

</body>
</html>

The result is:
BMW
Volvo
Saab

The continue statement “jumps over” one iteration in the loop.
Use it inside a loop (for…) ONLY.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to do a loop which will skip the step where i=3.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x="",i=0;
for (i=0;i<10;i++)
  {
  if (i==3)
    {
    continue;
    }
  x=x + "The number is " + i + "<br>";
  }
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

Notice:

  if (i==3)
    {
    continue;
    }

The result is:

The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9

NOTICE: You do not see the number 3!!! if i==3 “jumps over” 4!

My official WebSite >