Property accessors provide access to an object’s properties by using the dot notation or the bracket notation.
const person1 = {};
person1['firstname'] = 'Yogesh';
person1['lastname'] = 'Chauhan';
console.log(person1.firstname);
// output: "Yogesh"
const person2 = {
firstname: 'Yog',
lastname: 'Chauhan'
};
console.log(person2['lastname']);
// output: "Chauhan"
We can access features/properties in JavaScript using the following different ways.
object.property => dot notation
object['property'] => bracket notation
Lets try to add a property to the person1 object using bracket operator.
person1['middlename'] = "Yogi";
console.log(person1['middlename']);
//Output
Yogi
console.log(person1);
//Output
{ firstname: 'Yogesh', lastname: 'Chauhan', middlename: 'Yogi' }
We can add the same property to the person1 object using dot operator as well.
person1.middlename = "Yogi";
console.log(person1.middlename);
//Output
Yogi
console.log(person1);
//Output
{ firstname: 'Yogesh', lastname: 'Chauhan', middlename: 'Yogi' }
Credit: MDN Docs
features object-oriented objects property