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 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
What happens when we add Numbers and Strings in JavaScript?JavaScriptLearn to create your skill bar using CSSCSSHow to embed YouTube or other video links in WordPress?WordPressWhat is Git?MiscellaneousCanvas Drawing in HTML5HTMLSlider animation using CSS transform propertyCSSHow to send and receive query strings via links in Angular 9?AngularHow to Install PHP Laravel on MacOS Catalina?PHPHow to add Lifecycle Methods to a Class in React?ReactDifferent Types of Functions in JavaScriptJavaScriptA quick introduction to API, REST API and PostmanMiscellaneousAmpersand (Parent Selector) in SCSS (Sass)SCSS