What if I told you JavaScript had a limited form of the infamous goto statement? Surprised? Read on.
Labeled Statements in JavaScript
It is possible to add label identifiers to JavaScript statements and then use these identifiers with the break and continue statements to manage program flow.
While it might be better to use functions instead of labels to jump around, it is worth seeing how to jump around or interrupt loops using these. Let’s take an example:
// print only even numbers
loop:
for(let i = 0; i < 10; i++){
if(i % 2) {
continue loop;
}
console.log(i);
}
//0, 2, 4, 6, 8
// print only values less than 5
loop:
for(let i = 0; i < 10; i++){
if(i > 5) {
break loop;
}
console.log(i);
}
// 0, 1, 2, 3, 4, 5
There is a subtle difference between when labels can be used:
- break statements can apply to any label identifier
- continue statements can only apply to labels identifying loops
Because of this, it is possible to have the sample code below (yes it’s valid JavaScript too!)
var i = 0;
block: {
while(true){
console.log(i);
i++;
if(i == 5) {
break block;
console.log('after break');
}
}
}
console.log('outside block');
// 0, 1, 2, 3, 4, outside block
JavaScript Code Blocks
- continue wouldn’t work in the above scenario since the block label applies to a block of code and not a loop.
- The {} after the block identifier signify a block of code. This is valid JavaScript and you can define any block by wrapping statements inside {}. See an example below
{
let i = 5;
console.log(i);
}
// 5
Should I use this?
This is an arcane corner of JavaScript and I personally have not seen any code using this. However if you have a good reason to use this, please do add comments and references to the documentation. Spare the next developer after you some effort…
Reblogged this on #Barki2017 #iPDev 👑🇲🇦💯💻🔬.
LikeLike