add property to object javascript – How to Add Property to an object in JavaScript?

add property to object javascript Square Bracket Notation to add a property in JS Object, Modify a Property of a Javascript Object and Dynamically add property to object javascript.

add property to object javascript

There’re a 5 ways to add properties to an object in JavaScript Example.

memberObject.result = 1;

memberObject['result'] = 1;
memberObject['result-bar'] = 1;

Example

var memberObject = { Name: "Virat" };

memberObject.Age = 28;
console.log(memberObject.Age)

memberObject['Country'] =  "India"
console.log(memberObject.Country)

Javascript adds a property to Object.

let memberObject = {
  name: 'Darshini',
  age: 27,
  education: 'MCA'
};

console.log(memberObject)

memberObject.school = 'DSP';
console.log('After adding a property using dot syntax');
console.log(memberObject);

Result

{ name: 'Darshini', age: 27, education: 'MCA' }
After adding a property using dot syntax
{ name: 'Darshini', age: 27, education: 'MCA', school: 'DSP' }

Square Bracket Notation to add a property in JS Object

memberObject['school'] = 'DSP';

// app.js

let memberObject = {
  name: 'Darshini',
  age: 27,
  education: 'MCA'
};

console.log(memberObject)

memberObject['school'] = 'DSP';
console.log('After adding a property using square bracket syntax');
console.log(memberObject);

Result

{ name: 'Darshini', age: 27, education: 'MCA' }
After adding a property using square bracket syntax
{ name: 'Darshini', age: 27, education: 'MCA', school: 'DSP' }

don’t miss : Javascript Object Class

Also Read This πŸ‘‰   Most Useful Laravel String Functions(helpers)

Modify a Property of a Javascript Object

// app.js

let memberObject = {
  name: 'Darshini',
  age: 27,
  education: 'MCA'
};

console.log(memberObject)

memberObject['age'] = 26;
memberObject['name'] = 'Rakesh';
console.log('After modifying a property using square bracket');
console.log(memberObject);

Result

{ name: 'Darshini', age: 27, education: 'MCA' }
After modifying a property using square bracket
{ name: 'Rakesh', age: 26, education: 'MCA' }

I hope you get an idea about add property to object javascript.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.