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

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
Create dynamic selectors using SCSS (Sass)SCSSLearn to Implement Estimated Reading Time using PHP Part 2: Final Implementation with Source CodePHPHow get_template_part helps write reusable code in WordPress?WordPressHow different is Handling Events in React vs HTML DOM?ReactHow to include CSS and JavaScript files in your WordPress plugin?WordPressHow to create a Star Ratings using CSS?CSSHow to create a blurry text effect using CSS?CSSAngular 9 time clock update every minute, second, hourAngularHow to Use password_hash and password_verify to Secure Your User’s Data (Especially Passwords)?PHPHow to add transparent text on top of an image using CSS?CSSGive buttons accessible namesUI/UXHow to catch .keypress() on body using jQuery?jQuery