Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object literal notation differences in JS

Is there a difference between how JavaScript handles the following two declarations?

var foo = {
    foo : true,
    bar : 1
};

var foo2 = {
    "foo" : true,
    "bar" : 1
};

JavaScript seems to treat them the same. If they really are the same then, is there a "correct" or preferred way to declare this?

like image 869
Ervin Avatar asked Oct 10 '13 13:10

Ervin


2 Answers

Either form is fine for "initializing" an object (aka. declaring an object literal).

Property identifiers may be either names, numbers, or strings but they are all interpreted as strings:

var foo = {
  foo  : true,
  "bar": true,
  3    : true
};

See the ECMA-262 5th Edition Language Specification § 11.1.5 for more details.

Note that the PropertyName construct might have changed in the 5th edition (as many things did) so browsers that do not support the most recent version of JavaScript might implement a different version of ECMAScript.

Note also that JSON defines objects as sets of string/value pairs and strings are enclosed by quotation-marks:

var fooJSON = '{"foo":true,"bar":true,"3":true}';
like image 57
maerics Avatar answered Sep 29 '22 07:09

maerics


Your first sample is not json

{
    foo: true,
    bar: 1
}

enter image description here

So your second code (jsonlint) IS json.

 {
    "foo": true,
    "bar": 1
}

Regarding your actual question , they are both the same.

Regarding the comment :

If they are the same, but if the first example is not json, but the second is json, what is the difference?

Let's say I have this string which should(but is not) represent json string representation :

This string comes from the server :

" {foo: true,bar: 1}"

Now I want to Parse it.

Running

JSON.parse(" {foo: true,bar: 1}")

Will fail :

SyntaxError: Unexpected token f

However :

JSON.parse("{\"foo\": true,\"bar\": 1}")

Will do just fine

Object {foo: true, bar: 1}

So here is a difference (one difference example) .

Speaking of how JS see/treats both objects (Objects !!! , I didn't say json cuz the first one is not json) - they are the same.

PS , another helpful feature is that props are considered as strings even if you didnt use "myProp" :

example :

var a={myProp:1};  //notice no `"`
var b="myProp"; 
 a[b]=2; 
alert(a.myProp) //2
like image 33
Royi Namir Avatar answered Sep 29 '22 07:09

Royi Namir