inthenameofmusik
inthenameofmusik

Reputation: 623

Odd Object Quirk - JavaScript - Beginner

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?

Upvotes: 3

Views: 66

Answers (1)

user663031
user663031

Reputation:

{} 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

Upvotes: 7

Related Questions