inthenameofmusik inthenameofmusik - 2 years ago 63
Javascript Question

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?

Answer Source

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

Some references:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download