let original = {name: 'Joel', favoriteFood: 'oranges', age: 26};
let happyBirthday = {...original, age: 27};
happyBirthday will be an object that is identical to original but with the age overwritten.
So that would result in an object like this:
{name: 'Joel', favoriteFood: 'oranges', age: 27} // Notice the age
Answer from Pedro Filipe on Stack OverflowQuick question about ES6 spread operator on objects
Spread Operator vs Rest Parameter
spread vs rest syntax in JS, a little confused.
[AskJS] Who first used the term "spread operator" re spread syntax ...?
It was me. I coined the term “spread operator”.
It was a lonely night in 1993. I was angry at the world and I needed an outlet. I thought that by introducing an incorrect term to the javascript community, I could spread some of my pain to save myself at the expense of others.
I had no idea the impact I was going to cause on the javascript community and the world at large. I am horrified to witness you suffering from my mistake all these years later. I am truly sorry. I would do anything to go back and fix things.
Is there any way you could forgive me?
More on reddit.comlet original = {name: 'Joel', favoriteFood: 'oranges', age: 26};
let happyBirthday = {...original, age: 27};
happyBirthday will be an object that is identical to original but with the age overwritten.
So that would result in an object like this:
{name: 'Joel', favoriteFood: 'oranges', age: 27} // Notice the age
Objects cannot have duplicate keys. If you assign a key to an object when that object already has said key, or write an object initializer with duplicate keys, the prior value at that key will be overwritten:
const obj = {
foo: 'foo',
bar: 'bar',
};
obj.foo = 'new';
console.log(obj);
const obj = {
foo: 'foo',
bar: 'bar',
foo: 'new',
};
console.log(obj);
When using object spread, the same sort of thing is going on. If you add a key-value pair when a prior key already exists in the object initializer (by spread or otherwise), the prior value will be overwritten.
let happyBirthday = {...original, age: 27};
is very similar to
// Create a new object with all properties of `original`:
let happyBirthday = Object.assign({}, original);
// Assign to the `age` property of the new object:
happyBirthday.age = 27;