What's the best way to break from nested loops in Javascript?
//Write the links to the page. for (var x = 0; x < Args.length; x++) { for (var Heading in Navigation.Headings) { for (var Item in Navigation.Headings[Heading]) { if (Args[x] == Navigation.Headings[Heading][Item].Name) { document.write("<a href=\"" + Navigation.Headings[Heading][Item].URL + "\">" + Navigation.Headings[Heading][Item].Name + "</a> : "); break; // <---HERE, I need to break out of two loops. } } } }
The break statement, which is used to exit a loop early. A label can be used with a break to control the flow more precisely. A label is simply an identifier followed by a colon(:) that is applied to a statement or a block of code.
Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).
return always exits the current function. If you need to exit a loop you should be using break which terminates the current loop, label or switch statement. Thank you!
Just like Perl,
loop1: for (var i in set1) { loop2: for (var j in set2) { loop3: for (var k in set3) { break loop2; // breaks out of loop3 and loop2 } } }
as defined in EMCA-262 section 12.12. [MDN Docs]
Unlike C, these labels can only be used for continue
and break
, as Javascript does not have goto
.
Wrap that up in a function and then just return
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With