JS break statement in loop breaks the current loop only, not all of them. You have to use a boolean variable to break (break nested loop) out of the enclosing loop in JavaScript.
By default, the only innermost loop is escaped but you can achieve the behavior you expect by a self-enclosing function and a return statement.
(function(){
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (i == 3) {
return;
}
document.write(i + '*' + j + '<br>');
}
}
})()
Example break the nested loop in JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<head>
<script>
let b = false
for (i = 0; i < 5; i++) {
for (j = 0; j < 2; j++) {
console.log(i,j)
if (i == 2) {
b = true;
console.log("Break")
break;
}
}
if(b) break
}
</script>
</head>
<body>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS break loop topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version