DEV Community

Discussion on: What Javascript Spread Operator is, How It Works and How to Use It

Collapse
 
jdforsythe profile image
Jeremy Forsythe

The spec does not say it copies the value of the object, it says "keys and their values are copied onto a new object". tc39.es/proposal-object-rest-spread/

It is well know that making a "copy" of a primitive copies the value and making a "copy" of an object also copies the value, but the value is a reference to that object and not a clone of the object. This is what people refer to when they say copy "by reference" and is the source of the value vs reference debate which turns out to be a mostly semantic debate. JS copies by value but sometimes the value is a reference.

The proposal for this operator specifically calls it a "shallow clone (excluding prototype)" and it's just syntactic sugar for Object.assign() github.com/tc39/proposal-object-re...

Object.assign is 19.1.2.1 in the spec and you'll see there's no recursion and therefore it's not a deep copy/clone. It loops through the OwnPropertyKeys once and does a Get from the source and a Set on the target. It does not evaluate the OwnPropertyKeys of the value if the value is an object.