When to Use Dot Notation to Access Object Properties in JavaScript?

Dot notation can be used to access a JavaScript object property whose identifier name:

  • Has unicode letters, $, _, or digits (0-9);
  • Does not start with a digit.

For example:

const obj = { foo123: 'bar', $foo: 'baz', _foo_: 'qux' };

console.log(obj.foo123); // 'bar'
console.log(obj.$foo); // 'baz'
console.log(obj._foo_); // 'qux'
const obj = { '123foo': 'bar' };

// SyntaxError
console.log(obj.123foo);

If you wish to access a property that starts with a number, a property that has a hyphen or space, or a dynamic property, then you can use the bracket notation to access object property instead.


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.