Search code examples
javascriptnode.jsconsoletokenunexpected-token

Why does Node.js/JavaScript evaluate a:1 to 1?


Any explanation behind this evaluation in Node.js/JavaScript console:

> a:1
1

Trying to assign to variable throws error:

> x = a:1
Thrown:
x = a:1
     ^

SyntaxError: Unexpected token :

As leaving only a: in JS console does:

a:
VM138:3 Uncaught SyntaxError: Unexpected token }(…)

While in Node.js REPL:

> a:
... 3
3

Solution

  • When the start of the a is parsed as the beginning of a statement, it's interpreted as a label (which is something that can be used to break out of nested loops).

    outer:
    for (let i = 0; i < 10; i++) {
      console.log('outer loop iteration');
      for (let j = 0; j < 10; j++) {
        if (i === 3) {
          break outer;
        }
      }
    }

    But, unfortunately, labels are permitted even when they're not connected to loops, so having one where it doesn't seem to do anything doesn't throw a syntax error. As a result, the line

    a:1
    

    is interpreted as

    a: // label named a
    1  // unused expression
    

    If the start of the a is not at the beginning of a statement, it cannot be parsed as a label, so the colon only makes sense as part of a key-value pair - so if the Javascript text being parsed is not part of an object literal, it will throw a syntax error, as it does with your x = a:1 code.

    For the console, labels don't make any sense unless they're followed by code that could possibly use the label. If you type code into the console, and that code includes a label on the top level, that label will only be defined as long as the just-entered code runs. So defining a label as the final line in such code will result in that label never being accessible, which may be why the console throws the error (or, in my case on Chrome 76, refuses to execute the code, and instead just gives me a new line to continue typing on).