Labeled statements in Javascript2 min read

Naming in Javascript world
Labeled statements are just that, labels.
Using label statement we name loops or blocks of code in Javascript.
What do we get of it?
Well, that way, we easily refer back to the code, later if we need to!
Most obvious usage is in for loops.
i.e.:
[syntax_prettify linenums=”linenums”]
for (let i = 0; i <= 10; i++){
console.log(i);
}[/syntax_prettify]
Result of the above code is:
[syntax_prettify linenums=”linenums”]0,1,2,3,4,5,6,7,8,9,10[/syntax_prettify]
Handling this for loop is quite easy.
But what if we have two, or more, loops which are nested!?
for (let a = 0; a <= 10; a++){
console.log(a);
for (let b = 0; b <= 10; b++){
console.log(b);
}
}
And above that, what if we want to do some logic using continue or break?
[syntax_prettify linenums=”linenums”]for (var a = 0; a < 10; a++) {
for (var b = 0; b < 10; b++) {
if (a === 5) continue;
if (b === 4) break;
console.log(
${a} & ${b}
);
}
}
As you can see, things get more messy.
You have to be more carefull to read which loop are you continuing and which breaking.
LABEL TO THE RESCUE
But labeling each for loop makes our life, so much, easier!
loop-a:for (var a = 0; a < 10; a++) {
loop-b: for (var b = 0; b < 10; b++) {
if (a === 5) continue loop-a;
if (b === 4) break loop-b;
console.log(${a} & ${b});
}
}
This way we know exactly which loop is to continue and which one is to break.
Although labels are not that common, at least in my professional career i barely saw them in code, it’s good to know about this feature.
Particulary, why is this feature good to know? Well, obviously, for easier looping and because it’s pretty used in a new Javascript framework.
So stay tuned for my next post. As i’ll give some overview in a new kid on the block JS framework.

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Did you stumble upon a…

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Little chit-chat Hi! Let me…