Borislav Hadzhiev
Fri Nov 12 2021·2 min read
Photo by Diego PH
Use bracket notation to access a key that contains a space in an object, e.g.
obj['my key']
. The bracket []
notation syntax allows us to access an
object's key, even if it contains spaces, hyphens or special characters.
// ✅ Access key with space const obj1 = {'first name': 'Tom'}; console.log(obj1['first name']); // 👉️ "Tom" // ✅ Update key with space obj1['first name'] = 'Alice'; console.log(obj1); // 👉️ {'first name': 'Alice'}
There are two ways to access properties in an object:
A general rule of thumb followed by most developers is to use dot notation, unless the property in the object contains spaces, hyphens or starts with a number.
In all of the aforementioned scenarios, you have to use the bracket []
notation syntax.
Similarly to reading the value of a key that contains a space, we can use bracket notation to update the value.
You can also mix and match - use bracket notation where necessary and use dot notation in all other cases.
const obj1 = { person: { 'first name': 'Tom', }, }; console.log(obj1.person['first name']); // 👉️ "Tom" obj1.person['first name'] = 'Alice'; // 👇️ {person: {'first name': 'Alice'}} console.log(obj1);
We can access the person
property in the object using dot notation because it
contains no spaces.
However, the first name
property does, so we have to use bracket notation.
The alternative is to be consistent and use bracket notation to access both of the keys.
const obj1 = { person: { 'first name': 'Tom', }, }; console.log(obj1['person']['first name']); // 👉️ "Tom" obj1['person']['first name'] = 'Alice'; // 👇️ {person: {'first name': 'Alice'}} console.log(obj1);