I have read the answer on I don't understand about spread syntax inside objects but still don't quite understand the purpose of using (specifically) {...object}
.
What purpose does {...object}
serve?
I have tested this in the node REPL, say I made an object:
> const object = { foo: "hello", bar: "world" };
And use the spread operator inside a new object literal to refer to it:
> { ...object }
{ foo: 'hello', bar: 'world' }
The output is the same as just using the object itself:
> object
{ foo: 'hello', bar: 'world' }
What purpose does {...object}
serve?
It's not the same object. It makes a shallow copy of the object's own, enumerable properties (like Object.assign({}, object)
(MDN). You use it when you want...a copy, with the object's own, enumerable properties. :-D
For example, with any of several MVC or similar libraries, you might use it when updating state, since state shouldn't be modified directly:
this.setState(oldState => ({...oldState, prop: "new value"}));