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 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
What’s the difference between variables in CSS and SCSS (Sass)?CSSHow to show slider value in HTML5 range input using JavaScript?HTMLHow to create a horizontal scrolling menu with and without flex using CSS (or SCSS)?CSSThe Types of DatabasesMiscellaneousArray destructuring and Object destructuring in JavaScriptJavaScriptHow to animate list items using CSS and JavaScript?CSSWhat’s a Strict mode in JavaScript?JavaScriptWhat’s new in Constructor in PHP 8?PHPINNER JOIN in PostgresPostgresThe * arithmetic operator in Envision BasicEnvision BasicWhat is the difference between Loosely Typed Language and Strongly Typed Language?MiscellaneousAdd animated hamburgers menu using Hamburgers collection on GitHubCSS