While object property notation is usually written as myObject.property
, this will only allow characters that are normally found in JavaScript variable names, which is mainly letters, numbers and underscore (_
).
If you need special characters, such as space, ☺, or user-provided content, this is possible using []
bracket notation.
myObject['special property ☺'] = 'it works!'
console.log(myObject['special property ☺'])
In addition to special characters, property names that are all-digits will require bracket notation. However, in this case the property need not be written as a string.
myObject[123] = 'hi!' // number 123 is automatically converted to a string
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'
However, leading zeros are not recommended as that is interpreted as Octal notation. (TODO, we should produce and link to an example describing octal, hexadecimal and exponent notation)
See also: [Arrays are Objects] example.