Borislav Hadzhiev
Sat Nov 06 2021·1 min read
Photo by Artem Beliaikin
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.
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:
const obj = { country: 'Chile', }; console.log(obj.country); // 👉️ "Chile" console.log(obj['country']); // 👉️ "Chile"
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.
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.