Properties with special characters or reserved words

suggest change

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 ☺'])

All-digit properties:

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.

Feedback about page:

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


Objects:
* Syntax
* Properties with special characters or reserved words

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde