An object property can only be accessed using the bracket notation when/if a property name:
You may also use the bracket notation in place of the dot notation. However, the dot notation has a simpler syntax and should generally be preferred wherever possible.
Property Name With Space or Hyphen
If a property name is kebab-cased, or has spaces, then it can only be accessed using the bracket notation, for example, like so:
const obj = { 'foo-bar': 123, 'foo bar': 456 }; console.log(obj['foo-bar']); // 123 console.log(obj['foo bar']); // 456
Property Name Starting With a Number
When a property name starts with a number, it can only be accessed using the bracket notation, for example, like so:
const obj = { '123foo': 'bar' }; console.log(obj['123foo']); // 'bar'
This is also the case when accessing array indexes:
const arr = ['foo', 'bar']; console.log(arr[0]); // 'foo' console.log(arr[1]); // 'bar'
Dynamically Determined Property Name
Dynamic property names (i.e. property names that are not determined until runtime), can only be accessed using the bracket notation, for example, like so:
const obj = { 'user-123': 'john' }; const id = 123; console.log(obj[`user-${id}`]); // 'john'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.