Bob Napkin
Bob Napkin

Reputation: 566

Why does `{foo: 1}` evaluate to `1` in the console, and `{foo: 1, bar: 2}` results in an error?

I knew that {} is either an object or a block of code, but today my co-worker asked me why {foo: 1} works when entered into the console, but {foo: 1, bar: 2} generates an error.

Why does foo: 1 evaluate in the console to 1?

Upvotes: 3

Views: 494

Answers (3)

Marc B
Marc B

Reputation: 360872

It all depends on context:

function test() {
   var foo = {a:1}; // this is an object
   { alert('Hi mom!'); } // this is a block of code
   { a: 1 }; // also just a block of code, but `a:` is a label
}

If the {} block is used in an (in)equality test (==, ===, !=, etc...) or an assignment (=), then it's an object. All other contexts would be "just a block of code".

Upvotes: 0

Fathir Mohamad
Fathir Mohamad

Reputation: 91

i'm sorry not to comment under your post due to lack of reputation.

can you elaborate more on "Why I can print foo: 1 in JavaScript"?

If I run this code

var t = {foo: 1};

It will become the property for object "t". The same behaviour will be implement if you use this code

var t = {foo: 1, bar: 2};

You can access it by "t.foo" and "t.bar" and it will return the value either "1" or "2".

You can read the explanation of "object" here JavaScript Objects

Upvotes: 0

user663031
user663031

Reputation:

By itself, {a: 1} is a block statement, where a is a label.

Of course, in a context where an expression is expected, it is an object literal:

var o = { a: 1 };

Upvotes: 8

Related Questions