JavaScript labeled statement
- Planted:
Seen in Bytes yesterday:
Nested loops aren’t ideal, but sometimes they’re unavoidable. Given the nested loop below, how can we break out of the nested loop when
j === 2
?
The tl;dr is that you can label the outer for loop:
You can only use statement labels with break
and continue
, which I don't find myself using too often to begin with. You can't even console log a label—I tried, and it throws Uncaught ReferenceError: <label> is not defined
.
I'll admit that I actually learned about labeled statements a year or two ago when reviewing a coworker's PR, but I haven't come across one since. I think it's a neat language feature to stash in my back pocket.
Reply
Respond with your thoughts, feedback, corrections, or anything else you’d like to share. Leave your email if you’d like a reply. Thanks for reading.