3

According to the ECMAScript standard, labels can be applied to all statements.

This means that the following lines are valid:

myLabel: throw 'whatever'

as well as

function foo() {
  myLabel: return 'whatever'
}

console.log(foo())

But these labels appear to be unusable, which begs the question: why are they allowed? (Or maybe I have a fundamental misunderstanding)

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 3
    Probably because the first release of JavaScript was, more or less, thrown together in a weekend and now we're stuck with a few poor choices from back then … but that's speculation. I doubt the why of a language design choice from quarter of a century ago is documented anywhere. – Quentin Nov 29 '22 at 15:58
  • @Quentin It seemed like such a good idea at the time! – tadman Nov 29 '22 at 15:59
  • 2
    You can also do `return "foo"; console.log("bar")`. That's also allowed. JS doesn't differentiate terminal statements from any other statement. – VLAZ Nov 29 '22 at 16:01
  • 5
    Probably because it simplifies the grammar. I'd guess it's a legacy inherited from Java, which inherited it from C, which inherited it from Assembler, where you can label any statement. – Bergi Nov 29 '22 at 16:01
  • 1
    Best guess: because C [lets you label statements](https://www.c-programming-simple-steps.com/goto-statement.html) (for GOTO) and [Java as well](https://howtodoinjava.com/java/flow-control/labeled-statements-in-java/). @Bergi you beat me by 20 seconds lol. – Jared Smith Nov 29 '22 at 16:01
  • 2
    Notice you can do [fancy](https://stackoverflow.com/a/24663315/1048572) [things](https://stackoverflow.com/a/37469522/1048572) with labelled blocks. But yeah, labelled non-block statements (in which you cannot place a `break` or `continue`) are useless (just like many other forms of allowed code). – Bergi Nov 29 '22 at 16:04
  • 1
    This was before comments were invented, so you could document your code using labels. /s – GACy20 Nov 29 '22 at 16:05
  • 2
    @Quentin I note that labels [were not in ECMAScript v1](https://archives.ecma-international.org/1996/TC39/96-002.pdf). So the designed-in-ten-days observation is not strictly relevant. – Ben Aston Nov 29 '22 at 16:12
  • @Bergi Yay `myLabel: break myLabel`! (This is still useless) – FZs Nov 29 '22 at 19:13

1 Answers1

2

According to Brendan Eich, the author of JavaScript, this approach aped Java (the new hotness in 1996), and avoided the need for "dead label analysis":

Same as Java, IIRC. We didn't want to require engines to do dead label analysis. I know for sure I didn't want to when I first implemented in SpiderMonkey. This has led to unintended transposed javascript: labels (used to be URL schemes), but they're harmless.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Ben Aston
  • 53,718
  • 65
  • 205
  • 331