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

前端 未结 4 660
闹比i
闹比i 2020-12-21 09:03

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

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-21 09:45

    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

提交回复
热议问题