Access an Object Key that Contains a Space in JavaScript


Borislav Hadzhiev

Last updated: Nov 12, 2021


Photo from Unsplash

Access an Object Key that Contains a Space #

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:

  1. dot notation
  2. bracket notation

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.

You can use bracket notation in all cases where dot notation can be used, however you can't use dot notation if the object's key 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);
In my experience, JavaScript developers use dot notation where possible, and bracket notation only when necessary. This is what most linters suggest as well, as the dot notation syntax is more concise and easier to read.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.