Yogesh Chauhan's Blog

Accessing and Setting features of JavaScript Objects

in JavaScript on December 30, 2020

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


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Effects in ReactReactSorting Arrays in JavaScriptJavaScriptHow to add a Bar Chart in Angular App?AngularCheck If a String Contains a Specific Word in PHPPHPHow to use HTML picture Tag?HTMLHow to create and store JSON objects in localStorage using JavaScript?JavaScriptapply_filters function in WordPressWordPressA quick introduction to API, REST API and PostmanMiscellaneousComposing and Extracting Components in ReactReactKeyValuePipe in Angular 9AngularIntroduction to Angular modules Part 1: NgModule metadataAngularHow to vertically and horizontally align text and image block (without flex or grid) in CSS?CSS