Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

People also ask

Do object keys need quotes?

Unless an object key is a numeric literal or a valid identifier name, you need to quote it to avoid a syntax error from being thrown. In other words, quotes can only be omitted if the property name is a numeric literal or a valid identifier name.

What is the difference between for in and object keys?

keys(obj) returns only an array with the own properties of the object, while the for...in returns also the keys found in the prototype chain, in order the latter to be done extra check to the prototype of the obj is needed and then to the prototype of the prototype and so on and so forth, until the whole prototype ...

What are the differences between a single quote double quote smart quote and Backtick?

As you may have understood now, there is no real difference between using single quotes, double quotes, or backticks. You can choose one or multiple styles based on your preference. However, It is always good to stick to a single format throughout the project to keep it neat and consistent.

What is a string within quotation marks called?

A series of characters enclosed in matching quotation marks is called a literal string. The following examples both contain literal strings. SAY 'This is a REXX literal string.' /* Using single quotes */ SAY "This is a REXX literal string."


No, the quotes do not make a difference (unless, as you noted, you want to use a key that’s not a valid JavaScript identifier).

As a side note, the JSON data exchange format does require double quotes around identifiers (and does not allow single quotes).


From Unquoted property names / object keys in JavaScript, my write-up on the subject:

Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.

[…]

Bracket notation can safely be used for all property names.

[…]

Dot notation can only be used when the property name is a valid identifier name.

Note that reserved words are allowed to be used as unquoted property names in ES5. However, for backwards compatibility with ES3, I’d suggest quoting them anyway.

I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.

Screenshot


There is no difference here. Just a matter of style. One of the reasons for doing this is being able to use 'super' or 'class' as a key since those are reserved keywords.

Some people might be tempted to pass in a string with whitespace then call o['I can have whitespace'] But I would call that bad practice.


No, not to javascript. However, some JSON parsers will fail when the quotes around the keys are not present.