Access an Object Key that Contains a Space in JavaScript

avatar

Borislav Hadzhiev

Fri Nov 12 20212 min read

banner

Photo by Diego PH

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.

index.js
// โœ… 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.

index.js
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.

index.js
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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee