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 code block, but today my colleague asked me why {foo: 1} works as you type in the console, but {foo: 1, bar: 2} generates an error.

Why foo: 1 evaluate in console 1 ?

+3
source share
4 answers

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

Of course, in the context where the expression is expected, this is an object literal:

 var o = { a: 1 }; 
+8
source

{} do not always block, you can create an object with it (JSON style) for example

 var objectName = { propertyName:"Fiat", model:500, color:"white", methodName:function(a) { return a; } }; objectName.methodName('aa'); objectName.propertyName objectName[propertyName] 

and they are blocks

 if(...){ .. } while(...) { ... } try(..) { ...} catch { ...} 
0
source

It all depends on the 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 {} used in the equality test (in) ( == , === != , Etc.)) or assignment ( = ), then this is an object. All other contexts will be "just a block of code."

0
source

I'm sorry I did not comment on your post due to lack of reputation.

can you tell me more about "Why can I print foo: 1 in JavaScript"?

If I run this code

 var t = {foo: 1}; 

It will become a property for the t object. The same behavior will be implemented if you use this code

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

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

Here you can read the explanation of the "object" JavaScript objects

0
source

Source: https://habr.com/ru/post/1245011/


All Articles