YogeshChauhan . com

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

dreamhost

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 uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 7 How to disable right click and drag and drop of images using jQuery? May 7 How to render Lists in React? May 7 What’s the difference between variables in CSS and SCSS (Sass)? May 7 How to define variables in SCSS (Sass)? May 7 How to show and hide an element on click in React? May 5 Use inline if to make a shorter conditional syntax in React

You might also like these

How to change CSS with JavaScript?CSSJavaScript Data Types and Data Structures Things to RememberJavaScriptIntroduction to components and templates Part 1: Component MetadataAngularHow to show confirmation alerts with OK and cancel buttons using Swift 5?SwiftWhat’s a repository on Github?MiscSelect statement in Postgres with examplesPostgresKilling A Project Part 1: What criteria should be used to cancel/kill a project?MiscWhat Is a Graph Database?MiscWhat is the difference between float and double?Misc3 Types of Arrays in PHPPHPHow to use HTML picture Tag?HTMLHow to create two segues with two UIButtons on a single page (Swift 5.0)?Swift