There are two ways in which we can access the properties of a JS object. They are:

  1. Bracket Notion
  2. Dot Notation

Generally what most developers use is the dot notation, because of its simplicity. Here is an example of how dot notation will be used in a program.

const object = { one: "first", two: "second", three: "third" };

const firstProperty = object.one;
console.log(firstProperty);  //first  πŸ‘ˆ

Problem with dot notation

You saw how easy it was with dot notation. However, what if the object we are trying to access has key-pair values as follows:

const object2 = { "one-1": "first", "two-2": "second", "three-3": "third" };

Notice how the key names have a hyphen. In this case, we cannot use a dot notation, as javascript syntax wouldn't know it is a key string. This is where the bracket notation comes in handy. See the following example with different key names.


const object3 = { "one-1": "first", "two two": "second", "three.3": "third" };

const firstProperty = object3["one-1"];
const secondProperty = object3["two two"];
const thirdProperty = object3["three.3"];

console.log(firstProperty);  //first πŸ‘ˆ
console.log(secondProperty);  //second πŸ‘ˆ
console.log(thirdProperty);  //third πŸ‘ˆ

Here we used the bracket notation to represent different key names. As shown above, we can represent key names with hyphens, spaces or even with a dot in the middle without interfering with the javascript syntax. Using bracket notation, we can access any key names without the limitations of dot notation.

Accessing variables

You can also use bracket notation to access keys that are stored in a variable.

const object4 = { "one-1": "first", "two two": "second", "three.3": "third" };

const firstKey = "one-1"

const firstProperty = object4[firstKey];

You would be needing to use different combinations of these techniques in different circumstances.

Conclusion

Even though dot notation has its limitations, it is simple to use. i.e no brackets or quotes are needed. As a developer, you need to know both these notations as you will be using them interchangeably in different scenarios.