There are two methods by which we can access the properties of a JavaScript object.
Normally, developers are customed to using dot notion while programming due to its simplicity.
const object = { one: "first", two: "second", three: "third" };
const firstProperty = object.one;
console.log(firstProperty); //first πHowever, in the case of key names having spaces, hyphens or dots, we cannot use dot notation to access the object properties. This is where bracket notation comes in handy.
const object2 = { "one-1": "first", "two two": "second", "three.3": "third" };
const firstProperty = object2["one-1"];
const secondProperty = object2["two two"];
const thirdProperty = object2["three.3"];
console.log(firstProperty); //first π
console.log(secondProperty); //second π
console.log(thirdProperty); //third πBoth dot notation and bracket notation can be used interchangeably when accessing an object. Use the one that is convenient for the situation.
const object3 = {
blog1: {
"author name": "Sharooq",
},
};
const authorName = object3["blog1"]["author name"]; π
console.log(authorName); //Sharooq πThis code access an object property that is in a nested location. Here, we used both dot and bracket notations to achieve the same
However, we can stick with using bracket notation alone like in this code:
const object3 = {
blog1: {
"author name": "Sharooq",
},
};
const authorName = object3["blog1"]["author name"]; π
console.log(authorName); //Sharooq πYou can check out my other article "How to Access a JavaScript Object Property that has a Hyphen ( - ) in its Key Name" to have more understanding of this topic.
Thank you for reading. Check out my featured posts. See you in the next one.