3

I'm reading an article that says that {} is a valid JavaScript program.

I tried it and it worked fine.

Then I tried this and it worked:

{name:'Lord Stark'} <--- the entire program (not assigning it to a variable or anything)


But then I tried the following and it threw an error at the comma.

{name:'Lord Stark',reignsOver:'Winterfell'} <--- again this is the entire program


My question is, why does a plain object with more than one property (and consequently a comma), return an error unless assigned to a variable when an object with only a single entry does not?

10
  • The piece of code you posted works just fine. Both the snippets execute without error to me. Must have been a typo? Commented May 4, 2016 at 5:16
  • That's not an object with a property. It's a block containing a statement with a label. Notice that the output of the program {name:'Lord Stark'} is "Lord Stark", not {name: "Lord Stark"}. Commented May 4, 2016 at 5:17
  • Also, I can't find anywhere on that page that says that {} is a valid JavaScript program. It says that {} is a JavaScript object literal, but an object literal is not a program. Commented May 4, 2016 at 5:23
  • ecma-international.org/ecma-262/6.0/#sec-block Commented May 4, 2016 at 5:24
  • developer.mozilla.org/en/docs/Web/JavaScript/Reference/… Commented May 4, 2016 at 5:25

1 Answer 1

7

{} is an empty block.

{name: 'Lord Stark'} is a block with a label, and a string (which will do nothing).

{name: 'Lord Stark', reignsOver: 'Winterfell'} is a block, which starts off with a label again, then has string which will do nothing, then a comma operator, then an undefined variable reignsOver, then a colon, which is invalid syntax.

The {} will be interpreted as an object only in an expression context, such as var x = {name: 'Lord Stark', reignsOver: 'Winterfell'};.

Note that the console may exercise some smarts and try to figure out what you are doing, and might handle {a: 1, b:2} "correctly" as an object. To see how something is executed as a block, you could try typing in if (1) {name: 'Lord Stark', reignsOver: 'Winterfell'}.

The article you reference is not exactly right:

The curly brackets mean that this is an object and it can contain other objects within the curly brackets. Believe it or not this is a valid JavaScript program. If you run it, it creates an empty object which promptly disappears again as the program comes to an end.

Actually, a stand-alone JS program of the form {} is not an object, it's an empty block.

Some references:
http://www.ecma-international.org/ecma-262/6.0/#sec-block
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/block
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/label

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.