JavaScript objects are incredibly flexible, allowing you to add, modify, and remove properties at any time. In this blog post, we’ll explore various ways to add properties to a JavaScript object.
Adding properties using dot notation
One of the most common ways to add a property to an object is by using the dot notation. You can simply write the object name followed by a dot, then the property name, and finally assign a value to the property using the equals sign.
const person = {};
person.name = 'John';
person.age = 25;
console.log(person);
// Output: { name: 'John', age: 25 }
Adding properties using bracket notation
In some cases, you might want to use a variable or an expression to define the property name. In such scenarios, you can use the bracket notation to add properties to the object.
const person = {};
const propertyName = 'age';
person['name'] = 'Jane';
person[propertyName] = 30;
console.log(person);
// Output: { name: 'Jane', age: 30 }
Adding properties using Object.assign()
If you want to merge properties from one object to another, you can use the Object.assign() method. This method takes two or more objects as arguments and copies the properties from the source objects to the target object. It returns the modified target object.
const person = { name: 'Jack' };
const newProperties = { age: 35, occupation: 'Engineer' };
Object.assign(person, newProperties);
console.log(person);
// Output: { name: 'Jack', age: 35, occupation: 'Engineer' }
Adding properties using the spread operator
Another way to merge properties from one object to another is by using the spread operator (ES6 feature). The spread operator allows you to expand the properties of one object into another object literal.
const person = { name: 'Emma' };
const newProperties = { age: 28, occupation: 'Designer' };
const updatedPerson = { ...person, ...newProperties };
console.log(updatedPerson);
// Output: { name: 'Emma', age: 28, occupation: 'Designer' }
In this blog post, we’ve covered various ways to add properties to a JavaScript object. You can choose the method that best suits your needs, whether it’s using dot notation, bracket notation, Object.assign(), or the spread operator.