How and when to use "Labels" in Javascript?

Asked

Viewed 436 times

9

In objects/JSON we use : for keys and values, for example:

{x: 1}

As discussed in How to use the two points in Javascript?

However, I was working on a small script to try to detect the JSON format before the parse to avoid many Try/catch possible that I might need to maybe do and I came across this:

foo:console.log([1, 2, 3]);

Note that it’s not an object, so I tested this:

foo:foo:console.log([1, 2, 3]);

It returns the error:

"Uncaught Syntaxerror: Label 'foo' has already been declared",

I believe by the error message this is "Labels", then how and when we can use Javascript Labels? Is there any detail that differentiates the JS Label from other languages?

  • tip: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

1 answer

6

The Labels are to be used in instructions break and continue. They are inherited from C, C++ and Java, and also exist in many other languages such as C#, Pascal family languages, Visual Basic family languages, and others. For example:

a: for (var i = 0; i < 10; i++) {
    document.write("<br>");
    for (var j = 0; j < 10; j++) {
        if (i == 5 && j == 5) continue a;
        document.write("*");
    }
}

May also be used with break in common blocks:

s: {
    document.write("antes<br>");
    break s;
    document.write("você não vai ver isto!<br>");
}
document.write("depois");

The use of this feature in Javascript is very rare and makes sense only in very specific situations. In its predecessors it was widely used in conjunction with the gotos, but as these were not added to Javascript, there were few circumstances where they would still be useful (but as there were still some, it was not deleted from the language).

I’ve used this feature of the language a few times in answers here from Sopt. In Javascript, I used in this answer and our friend Anderson Carlos Woss used in his reply. In Java (which has the same operation in this case), I used these here: 1, 2, 3, 4 and 5. See these answers for more real use examples.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.