Skip to main content

How to access an object property with a Hyphen in JavaScript

Implement bracket notation to access an object property with a hyphen. If the property contains a hyphen, space, or special symbols, you have to use bracket notation.

To access an object property with a hypen can be accessed in two ways:

  1. . (dot Notation)
  2. [] (bracket Notation)
const object = {
'object-hypen': '1',
'has space': '2',
'with.dot': '3',
};
console.log(object['object-hypen']); // 1
console.log(object['has space']); // 2
console.log(object['with.dot']); //3

Usually, all the developers use bracket notation, when the object property has a hyphen or a space.

Dot Notation

The two ways to access properties on an object are:

const object = {
key: 'United States is the Best Country in the world',
};

console.log(object.key); // "United States is the Best Country in the world"
console.log(object['key']); // "United States is the Best Country in the world"

Bracket Notation

info
  1. Use dot notation, whenever necessary.
  2. when there are special characters involved like hyphen, or is stored in a variable in such cases bracket notation is a viable option.
const object = {
'key-with-hyphen': 'United States is the Best Country in the world',
};
console.log(object['key-with-hyphen']); // "United States is the Best Country in the world"

Bracket Notation for values stored in a variable

const object = {
continent: 'North America',
};

const key = 'continent';

console.log(object[key]); // North America

As you can see, the key in object[key], gets replaced as object['continent'] and the console, displays North America.


Thanks for reading!

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