Why do labels exist?

Why do labels exist in javascript?

var i = 0; usefulLabel://why do I exist? while(i <= 10){ document.writeln(i); i++; if(i > 5) break;// usefulLabel; } 

The above code does not need a shortcut at all (it works with or without the name of the marked shortcut). And given that Douglas Crockford did not completely condemn them:

Shortcuts

Signs of operators are optional. Only these statements should be labeled: while, do, for, switch.

Are they ever considered good practice for implementation? For me, these things are terribly close to the infamous goto instruction in some languages.

+6
source share
3 answers

If you want to break out of an outer loop from a nested loop, you need a shortcut.
If you need it, you should consider reorganizing your code to make it easier. (although this is not always possible)

+8
source

Yup, they exist for the GOTO and SWITCH statements. I basically see that they are used for nothing else, and will never think about marking a section of code just for fun.

+2
source

The code sample you provided does not use the shortcut at all, as it is not mentioned anywhere.

More on labels here:

https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#label_Statement

Here is an example of a loop break:

 var x = 0; var z = 0 labelCancelLoops: while (true) { console.log("Outer loops: " + x); x += 1; z = 1; while (true) { console.log("Inner loops: " + z); z += 1; if (z === 10 && x === 10) { break labelCancelLoops; } else if (z === 10) { break; } } } 

I would suggest using labels to a minimum, as they confuse reading and monitoring the flow of execution. Like GOTO.

0
source

Source: https://habr.com/ru/post/899997/


All Articles