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. Wh
Solution 1:
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
vart= {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
Solution 2:
{}
not block always, you can make 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're blocks
if(...){ .. }
while(...) { ... }
try(..) { ...} catch { ...}
Solution 3:
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".
Post a Comment for "Why Does `{foo: 1}` Evaluate To `1` In The Console, And `{foo: 1, Bar: 2}` Results In An Error?"