When to Specify JavaScript Object Property Names Using Quotes?

Find out when to use quotes around JavaScript object keys

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).


Hope you found this post useful. It was published . Please show your love and support by sharing this post.