Skip to main content

How to Access an Object Key that Contains a Space in JavaScript

Implement the bracket notation to access an object property(key) that contains a space in an object. The bracket[] notation syntax is always used, when keys contain spaces, hyphens or special characters.

const object1 = {'key space': 'America'};
console.log(object1['key space']); // "Tom"

object2['key space'] = 'North America';
console.log(object2); // {'key space': 'North America'}

The are two ways to access an object property (keys):

  1. . dot notation - Always use the dot notation, unless the keys have a special character like space, hyphens or it starts with a number
  2. [] bracket notation - For special cases implement the bracket notation as you can not implement dot notation if the object property(Keys) contains spaces, hyphens, or starts with a number.

Bracket Notation Scenarios:

Below are some examples, of Bracket notation, that contains a space, a hyphen or a special character.

You can mix and match both the scenarios, like using the dot notation and bracket notation, but it is not recommended as it decreases the readability of the code.

const object = {
a: {
'key with space': 'Value',
},
};
console.log(object.a['key with space']); // 'Value'

object.a['key with space'] = '100';
console.log(object); // {1: {'key with space': '100'}}

The a object property is accessed as it does not contain any space. Having said that if it contains a space, we need to implement the bracket notation as shown below.

const object = {
a with space: {
'key with space': 'Yo',
},
};
console.log(obj1['a with space']['key with space']); // 'Yo'
info
  • Dot Notation: Use by default, maintain consistency and readability of the code.
  • Bracket Notation: Implement when the object property has a special character like space, hyphen etc.

Most linters suggest dot notation is more concise and easier to read.


Thanks for reading!

If you liked this article, feel free to check out and explore more topics @socialcol.com