Breaking the Loop in JavaScript
In this post, we will see how to break out from a loop in JavaScript. When we work with array or an object sometime we need to iterate the each element to process the data.
We can jump out at any time of execution while looping using the break
statement. The break statement terminates the execution of the current loop.
Syntax
break; //terminates the innermost enclosing loop or switch. break [label]; //terminates the specified enclosing labeled statement.
Let’s look at how the break statement works with the loops with the simple scripts.
for loop
var lang = ["JAVA", "JavaScript", "Python", "CSS", "nodeJs", "SQL"]; for (let i = 0; i < lang.length; i++) { if(lang[i] == "CSS") break; console.log(lang[i]); } /* Output will be like below JAVA JavaScript Python */
for..of loops
var lang = ["JAVA", "JavaScript", "Python", "CSS", "nodeJs", "SQL"]; for (x of lang) { if(x == "CSS") break; console.log(x); } /* Output will be like below JAVA JavaScript Python */
for..in loop
var carProp = {name:"Audi", color:"Black", model:"Audi A6"}; var x; for (x in carProp) { if(x == 'model') break; console.log(carProp[x]); } // Audi Black
while loop
let lang = ["JAVA", "JavaScript", "Python", "CSS", "nodeJs", "SQL"]; let i = 0 while (i < lang.length) { if (lang[i] === 'CSS') break console.log(lang[i]); i++ } /* Output will be like below JAVA JavaScript Python */