Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript object literals syntax error

Tags:

javascript

The following code produces a syntax error in Chrome and Firefox, but not Node.js:

{"hello": 1}

However, the following code works everywhere:

var x = {"hello": 1}

Also, the following works everywhere:

{hello: 1}

What is the explanation for this strange behavior?

like image 713
ipartola Avatar asked Jun 25 '13 13:06

ipartola


2 Answers

The NodeJS REPL evaluates code as an expression, by wrapping the code in parentheses, causing {"hello":1} to be ({"hello":1}) which is parsed successfully as an object literal.

Usually and elsewhere (in Chrome/Firefox's console), the curly braces are parsed as the delimiters of a block, like:

/*imagine if (true) */ {
    "hello": 1 // <-- What's this syntax? It's meaningless.
}

{hello:1} parses successfully, because hello in this context has the meaning of a label:

/*imagine if (true) */ {
    hello: 1;
} //        ^-- Automatic Semicolon Insertion
like image 109
Rob W Avatar answered Sep 22 '22 20:09

Rob W


The first example is not an object literal, it is a block. Blocks contain statements. The squence String literal, colon, Number literal is not a valid statement.

The second example is an object literal.

The third example is also a block, but you have replaced the string literal and colon with a label (which is allowed, but is pointless as there is no loop).

Context is important in JavaScript.

like image 32
Quentin Avatar answered Sep 19 '22 20:09

Quentin