0

Is there any difference between:

NewObject = {'foo': 'bar'}

And

NewObject = {foo: 'bar'}

For they seem to be working in the same way.

3
  • I'd like to know whether there is a difference in data types, for 'foo' is a string, but foo inside the object seems to be a variable, or is it seen as a string by js even though there are no parentheses Commented Nov 15, 2014 at 21:19
  • 1
    This is a language feature for javascript object literals. Commented Nov 15, 2014 at 21:25
  • I mean quotes not parentheses Commented Nov 15, 2014 at 21:29

2 Answers 2

2

No difference. Using quotes is required if the key name is a reserved word or contains special characters:

{ 'foo+2' : 'bar' }
{ 'finally': 'foo' }

Otherwise no quotes required.

Sign up to request clarification or add additional context in comments.

3 Comments

I'd like to know whether there is a difference in data types, for 'foo' is a string, but foo inside the object seems to be a variable, or is it seen as a string by js even though there are no parentheses
No, it is ALWAYS a string. If you want to pass a variable as key name, you have to use the [] syntax, for example: var NewObject = {}; NewObject[foo] = 'bar'; <-- this will use the foo variable rather than the "foo"-string. The notation NewObject.foo is equivalent to NewObject['foo']. It's up to you which one you prefer to use.
object literals can be treated as JSON so, if you plan to use it as JSON, JSON.stringify-ing your variable will add quotes automatically (not talking about special characters here), but if you create it manually using unquoted properties it'll result in an Invalid JSON. {name : "foo"} // invalid JSON
0

JavaScript does not have dynamic variables but you can create dynamic properties. For example:

arr['a' + 3] = 4;
console.log(arr.a3); //4 

The answer is that there is not difference.
In this case the appropriate way to do it is by using double quotes {"a3": 4} because that is the syntax for JavaScript object notation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.