To add a new property to an object in JavaScript, define the object name followed by the dot(.), the name of a new property, an equals sign, and the value for the new property.
let obj = {
name: 'Krunal',
age: 27,
education: 'Engineer'
};
console.log(obj)
obj.college = 'VVP';
console.log('After adding a property using dot syntax');
console.log(obj);
Output
{ name: 'Krunal', age: 27, education: 'Engineer' }
After adding a property using dot syntax
{ name: 'Krunal', age: 27, education: 'Engineer', college: 'VVP' }
You can see that we added a new property called college using dot syntax and logged the Object.
You can add dynamic properties to an object after the object is created, and let’s see how we can do that.
Using Square Bracket Notation to add a property in JavaScript Object
To add a property, use square bracket notation. The following demonstrates square bracket syntax.
obj['college'] = 'VVP';
Example
let obj = {
name: 'Krunal',
age: 27,
education: 'Engineer'
};
console.log(obj)
obj['college'] = 'VVP';
console.log('After adding a property using square bracket syntax');
console.log(obj);
Output
{ name: 'Krunal', age: 27, education: 'Engineer' }
After adding a property using square bracket syntax
{ name: 'Krunal', age: 27, education: 'Engineer', college: 'VVP' }
Square bracket syntax is also required when the property name is variable; for instance, if it is passed as the argument to a method, it is accessed in a for-in loop or is an expression to be evaluated, such as the following code.
let obj = {};
console.log(obj);
for (var i = 0; i <= 5; i++) {
obj['prop' + i] = i;
}
console.log(obj.prop4);
Output
{}
4
An expression with the object name, a dot, and a property name (obj.prop4) will evaluate the current value of that property. Our example first displays the value in the console log, then assigns the value to the variable val.
Square bracket syntax is required if a property name contains spaces or other special characters or includes the keyword reserved in JavaScript. Otherwise, errors will be your result.
Conclusion
To add the property, change the property’s value, or read a value of the property, use either dot syntax or square bracket notation.