Access an Object Property with a Hyphen in JavaScript

avatar

Borislav Hadzhiev

Sat Nov 06 20211 min read

Access an Object Property with a Hyphen #

Use bracket notation to access an object property with a hyphen, e.g. obj['with-hyphen']. There are two ways to access properties on an object - dot notation and bracket notation. If the property contains a hyphen, space, or special symbols, you have to use bracket notation.

index.js
const obj = { 'with-hyphen': 'value1', 'with space': 'value2', 'with.symbol': 'value3', }; console.log(obj['with-hyphen']); // ๐Ÿ‘‰๏ธ "value1" console.log(obj['with space']); // ๐Ÿ‘‰๏ธ "value2" console.log(obj['with.symbol']); // ๐Ÿ‘‰๏ธ "value3"

We used bracket notation to access an object property that contains a hyphen.

The two ways to access properties on an object are:

  • dot notation
  • bracket notation
index.js
const obj = { country: 'Chile', }; console.log(obj.country); // ๐Ÿ‘‰๏ธ "Chile" console.log(obj['country']); // ๐Ÿ‘‰๏ธ "Chile"
Most commonly developers use the dot notation syntax, unless the key name contains spaces, hyphens, special symbols, or is stored in a variable.

In any of these scenarios, you have to use bracket [] notation.

Here's the other common use case for bracket notation - they key is stored in a variable.

index.js
const obj = { country: 'Chile', }; const key = 'country'; console.log(obj[key]); // ๐Ÿ‘‰๏ธ "Chile"

If we were to access the property by using obj.key we would be accessing a property named key.

By passing the variable between the square brackets, it gets evaluated and allows us to access the country property.

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