What is the standard or best practice with regards to quotes on JavaScript keys?

Viewed 888

I have been going through several questions such as this to see if there is a standard practice/ best practice for whether to put quotes on keys in JavaScript or JSX or TSX. I, however, haven't found anything and would like to know (before building a huge project on bad practices) which is best between:

obj = {'foo': 'bar'}

and

obj = {foo: 'bar'}

Or better yet, is there some document I can refer to for this?

3 Answers

checkout the Airbnb JavaScript Style Guide. It has a standard set of guidelines and best practices.

  • 3.6 Only quote properties that are invalid identifiers. eslint: quote-props

Why? In general we consider it subjectively easier to read. It improves syntax highlighting, and is also more easily optimized by many JS engines.

// bad
const bad = {
  'foo': 3,
  'bar': 4,
  'data-blah': 5,
};

// good
const good = {
  foo: 3,
  bar: 4,
  'data-blah': 5,
};

ESLint docs have some input on this:

In many cases, it doesn't matter if you choose to use an identifier instead of a string or vice-versa. Even so, you might decide to enforce a consistent style in your code.

There are, however, some occasions when you must use quotes:

  • If you are using an ECMAScript 3 JavaScript engine (such as IE8) and you want to use a keyword (such as if) as a property name. This restriction was removed in ECMAScript 5.
  • You want to use a non-identifier character in your property name, such as having a property with a space like "one two".

Another example where quotes do matter is when using numeric literals as property keys:

var object = { 1e2: 1, 100: 2 };

IMO it's good to use quotes when needed.

Both work and it's up to you what you want to do but my university teacher did tell us not to use quotations so as to make it a bit different from string value hence our whole class adopted as standard practice

obj = {foo: 'bar'}
Related