How to use the spread operator to update an Object value with JavaScript?

Estimated read time 1 min read

In JavaScript, you can use the spread operator (...) to create a new object with an updated value. Here’s an example of how to use the spread operator to update an object value:

const obj = { 
  name: 'John', 
  age: 30, 
  city: 'New York' 
};

const updatedObj = { 
  ...obj, 
  age: 31 
};

console.log(updatedObj);
// Output: { name: 'John', age: 31, city: 'New York' }

In this example, the original object obj has a name, age, and city property. The spread operator is used to create a new object updatedObj, which includes all of the properties from the original object. However, the age property is updated to a new value of 31.

By using the spread operator to create a new object, we can easily update the values of individual properties while preserving the rest of the object’s properties. Note that if there are any properties in the new object that have the same name as properties in the original object, the values of those properties in the new object will override the values in the original object.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply