When to Specify JavaScript Object Property Names Using Quotes?

JavaScript object property names can be a string literal, numeric literal or identifier. Quotes for object keys are only needed when the object property name is not a valid:

For all other strings, you must quote the object property name, otherwise a SyntaxError will be thrown.

Specifying Unquoted JavaScript Identifiers as Property Names

Quotes are optional when specifying object property names that are valid JavaScript identifiers. For example, the following object keys don't require to be wrapped in quotes:

const obj = {
    foo: 'bar',
    foo123: 'bar',
    _foo_: 'bar',
    $foo: 'bar',
};

Object property names that are valid identifiers can be accessed using either the dot notation (i.e. object.property syntax) or the bracket notation (i.e. object['property'] syntax).

Specifying Unquoted Numeric Literals as Property Names

Quotes are optional when specifying object property names that are valid numeric literals. For example, the following object keys don't require to be wrapped in quotes:

const obj = {
    123: 'foo',
    12e34: 'bar',
};

Object property names that are valid numeric literals can only be accessed using the bracket notation (i.e. object[number] syntax without using quotes around the numeric literals).


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.