JavaScript Label — Rarely used JS Concepts
Here is everything you need to know about javascript labels
TLDR; JavaScript labels are the aliases for code statements which we can use with break
and continue
. Labels are loop breaker identifiers. Label’s are useful if we have nested loops and we want to break loops in-between.
Syntax For Creating Labels:
LabelName: (LabelName can be any user defined thing)
if(1) {
// your code
}
Now let’s understand some usage of it.
- It can be useful when we want to exit from nested loops. (Same for continue)
No need to use break multiple times, we can simply add label to the outer loop and use this name to break from anywhere inside the nested loops.
2. Label can be used to create named blocks, and break blocks in-between based on certain conditions:
continue
can’t be used inside block, it can only be used inside loops.
3. We can use labels to exit from if block, if any condition is not met inside the if block.
Here, if user failed
the exam, we don’t wan’t to run anything. But break
statement is not enough to exit from if block.
We have to add additional check inside if
block, to prevent execution of certain code.
With labels, we can directly exit from if block:
And that’s all for JavaScript labels. I hope it made you to learn something new.