DEV Community

Discussion on: JavaScript, stuff you've never heard of (probably): labeled loops?

Collapse
 
fraxken profile image
Thomas.G

You can label a code block too !

myLabel: {
    const something = fn();
    if (something) {
        break myLabel;
    }

    // Do work here!
}
Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

That's the spirit, take the wierd to the next level.

Does have the effect of early return without a function?

I think labels are just so out of place in js, cool as they are, they are not defined like variables and are more meta.

Saves writing an IFFE. Im certain this would be a touch faster then an IFFE (but it costs in reasoning about)

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀 • Edited

Interesting I doubt a nested labeled code block would work, for fun reasons. Perhaps if it where encapsulated ()

Collapse
 
rasata profile image
Rasata'Ninja • Edited

wow,So I just discovered that label exists in JS!
It seems that this give you a thinner control on loop breaking ! an example here