0

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?

mikemaccana
  • 110,530
  • 99
  • 389
  • 494

1 Answers1

4

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"}));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks @T.J.Crowder. I already check the question was a duplicate and there's no other answers. – mikemaccana Mar 10 '21 at 16:55
  • @mikemaccana - I wouldn't be surprised if there are some out there. It's really hard to search for this. I haven't found a good one yet. – T.J. Crowder Mar 10 '21 at 16:56
  • lol it's been marked as a duplicate of general purpose questions about what the spread syntax means. Which isn't the question. – mikemaccana Mar 10 '21 at 18:47
  • 1
    @mikemaccana The first is the _"catch all"_ for questions about operators/symbols that lacks an explanation for this shallow-copy use-case. The second one is wrong imho. The third one is not perfect but has good hints. The forth explains the details on your use-case. Not optimal but the last one should be enough for an answer on your question. – Andreas Mar 11 '21 at 08:48
  • @Andreas I'm not sure on the SO policy on when questions are different but answers from other questions help. But yes I agree - the first 3 links are irrelevant, the fourth has actual useful answers. – mikemaccana Mar 11 '21 at 08:55
  • @Andreas - Good analysis if you don't mind my saying so. I've moved the useful one to the top and removed the one that wasn't a good target for this. – T.J. Crowder Mar 11 '21 at 09:10
  • @T.J.Crowder if you wanted to make it narrower, just the 'Object copy using Spread operator actually shallow or deep?' would be the more relevant. – mikemaccana Mar 11 '21 at 10:17