Are Quotes Always Required When Accessing JavaScript Object Properties Using the Bracket Notation?

Find out if quotes are always needed when accessing JavaScript object keys using the bracket notation

Quotes are only required for object property names specified in the following way, when accessing them using the bracket notation:

When accessing object properties using the bracket notation, quotes are not needed for property names that are specified as:

Also, quotes are not needed when dynamically accessing object properties.

Accessing String Object Property Names With Bracket Notation

When accessing object keys specified as string literal using the bracket notation, quotes are required:

const obj = {
    foo: 'bar',
    'foo-bar': 'baz',
    'foo bar': 'qux',
};

console.log(obj['foo']); // 'bar'
console.log(obj['foo-bar']); // 'bar'
console.log(obj['foo bar']); // 'bar'

Accessing Identifier Object Property Names With Bracket Notation

When accessing object keys specified as valid JavaScript identifiers using the bracket notation, quotes are required:

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

console.log(obj['_foo_']); // 'bar'
console.log(obj['$foo']); // 'baz'
console.log(obj['foo123']); // 'qux'

Accessing Numeric Object Property Names With Bracket Notation

Object keys specified as numeric literals can only be accessed using the bracket notation, however, quotes are optional:

const obj = { 123: 'foo' };

console.log(obj[123]); // 'foo'
console.log(obj['123']); // 'foo'

This also applies to object keys specified using scientific notation numeric literals:

const obj = {
    12e3: 'foo',
    12e34: 'bar',
    12e+36: 'baz',
    1.23e+5: 'qux',
};

console.log(obj[12e3]); // 'foo'
console.log(obj[12e34]); // 'bar'
console.log(obj[12e+36]); // 'baz'
console.log(obj[1.23e+5]); // 'qux'

When accessing object property names that are defined using the scientific notation, quotes should always be omitted, otherwise the interpreter won't know whether you meant to access a string of the same type

Accessing Symbol Object Property Names With Bracket Notation

Object keys specified as Symbol can only be accessed using the bracket notation, without using quotes:

const sym = Symbol('a');
const obj = { [sym]: 'foo' };

console.log(obj[sym]); // 'foo'

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