-3

Possible Duplicate:
What is the difference between object keys with quotes and without quotes?

I mostly know JavaScript from using it, but there's something I don't understand yet.

What's the difference between these two object literals:

var obj1 = {
   myProp: '123'
};

var obj2 = {
   'myProp': '123'
};

Are they just 'synonyms', or is there a subtle difference?

Thanks!

Community
  • 1
  • 1
EsTeGe
  • 2,975
  • 5
  • 28
  • 42
  • 1
    @EsTeGe: Have you searched for the answer? As Bismark already mentioned, this question has been answered before. -1 – Tadeck Aug 05 '12 at 13:56

2 Answers2

3

In the object initializer syntax, keys can be numeric literals, identifiers, or strings.

var obj1 = {
    1e9: "123" //valid because it's a numeric literal
}

var obj2 = {
    $_ASd: "123" //Valid because it's a valid identifier I.E. you could make a variable called $_Asd
}

var obj3 = {
    $ hello world: "123" //invalid because it's not an identifier, I.E. you could not make a variable called $ hello world
}

var obj4 = {
    '$ hello world': "123" //valid because it's a valid string
}

After that the key is turned into a string regardless of what it was in the syntax, so in the case of 1e9 the key will be a string "1000000000".

Esailija
  • 138,174
  • 23
  • 272
  • 326
1

Nothing when there isn't an operator inside of it.

var obj1 = {
   my+Prop: '123' // illegal
};

var obj2 = {
   'my+Prop': '123' // legal
};
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Or a number at the start. The correct way to say it would be "when it's not a valid identifier". – Ry- Aug 05 '12 at 13:56