Break as the name suggests, is used to break out of a loop(i.e. for loop or while loop) before its execution is complete.
To make it a little simpler, let us take the below example.
Say you have a while loop that is used to document.write the numbers from 1 to 6.
<html> <body> <script language = "javascript" type = "text/javascript"> var x = 1 while (x <= 6) { document.write(x, ", ") x++ } </script> </body> </html>
But let us say, you want to break out of the while loop, if the value of x is 4. i.e. You want to get out of the loop, right after printing 1, 2, 3 and 4.
And we can achieve it using break statement.
Let us modify the above program using the break statement.
<html> <body> <script language = "javascript" type = "text/javascript"> var x = 1 while (x <= 6) { document.write(x, ", ") if (x == 4) { break } x++ } </script> </body> </html>
And all we have done is placed an if condition, right after the document.write statement, checking if the value of x is equal to 4. If so we break out of the loop.
if (x == 4) { break }
And the break statement helps to get out of the while loop.
Let us see another example of break using the for loop.
Say we have a for loop that prints all the letters of a String (i.e. Hello World).
<html> <body> <script language = "javascript" type = "text/javascript"> for (x of "Hello World") { document.write(x, ", ") } </script> </body> </html>
But let's say, we just want to document.write Hello. And omit the World.
And as we can see that Hello World is separated by a space (i.e. ' ').
Let us rewrite the program using break statement.
<html> <body> <script language = "javascript" type = "text/javascript"> for (x of "Hello World") { if (x == ' ') { break; } document.write(x, ", ") } </script> </body> </html>
And what we have done is, checked if the value of x is a white space (i.e. ' '). Because Hello World is separated by a space (i.e. ' ').
if (x == ' ') { break; }
And came out of the for loop with the break statement, printing just Hello.