Properties with special characters or reserved words

suggest change

Dot notation uses an IdentifierName. That includes letters, digits, _, $, and reserved words such as break. A reserved word can be an unquoted property name. It cannot be a variable name. An identifier cannot start with a digit.

Spaces, punctuation, most symbols, and user-provided text need bracket notation:

const myObject = {};
myObject['special property ☺'] = 'it works!'
console.log(myObject['special property ☺'])

All-digit properties:

A property name that is only digits is not a valid identifier, so it needs brackets. A number used as a key is converted with ToString. The brackets can hold an expression, not only a string literal.

const myObject = {};
myObject[123] = 'hi!' // number 123 is converted to the string "123"
console.log(myObject['123']) // notice how using string 123 produced the same result
console.log(myObject['12' + '3']) // string concatenation
console.log(myObject[120 + 3]) // arithmetic, still resulting in 123 and producing the same result
console.log(myObject[123.0]) // this works too because 123.0 evaluates to 123
console.log(myObject['123.0']) // this does NOT work, because '123' != '123.0'

A numeric literal with a leading zero is a syntax error in strict mode, including modules. In non-strict code, 0123 is a legacy octal literal, so myObject[0123] uses the key "83", not "0123". The string key "0123" is a different property. Hexadecimal literals such as 0x10 are also numbers, so the key is "16".

See also: Arrays are Objects.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents