How and when to use "Labels" in JavaScript?

8

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

{x: 1}

As discussed in What is the use of the colon in JavaScript?

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

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

Note that this is 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 think the error message is "Labels" , so how and when can we use Labels in JavaScript? Is there any detail that differentiates the Label in JS from other languages?

    
asked by anonymous 01.11.2017 / 20:58

1 answer

6

Labels are used to use break and continue statements. They are a feature 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("*");
    }
}

They can 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 goto s, but since these were not added to JavaScript, there were few circumstances left where they would still be useful (but as there were still some, it was not deleted from the language).

I have already used this language feature a few times in responses here from SOpt. In JavaScript, I used in this answer and our friend Anderson Carlos Woss used in this response from him . In Java (which has the same operation in this case), I used those here: 1 , 2 ,

01.11.2017 / 21:14