What are the differences between JavaScript's Object.assign() and Object spread?
Alex K
JavaScript provides two mechanisms for object manipulation:Object.assign() and object spread syntax ({...}) that achieve similar results but have some key differences:
1. Usage:
-Object.assign() is a method that takes an empty target object as the first argument and assigns properties from one or more source objects to the target object. It mutates the target object.
- Object spread syntax is a language feature that allows you to create a new object by copying properties from one or more source objects. It creates a new object without modifying the source objects.
2. Mutability:
-Object.assign() mutates the target object, modifying it in place.
- Object spread syntax creates a new object without modifying the source objects.
3. Shallow vs. Deep Copy:
-Object.assign() performs a shallow copy of the properties from the source objects to the target object. If a property value is an object or array, it is copied by reference rather than creating a new copy.
- Object spread syntax also performs a shallow copy, but it creates a new object and shallow copies the properties from the source objects to the new object. If a property value is an object or array, it is shallow-copied by reference.
4. Property Overwriting:
-Object.assign() overwrites properties with the same name in the target object if they exist in the source objects. If multiple source objects have properties with the same name, the right-most object's value will overwrite previous values.
- Object spread syntax follows the same property overwriting rule asObject.assign(). The right-most object's value will overwrite previous values.
5. Array/Object Spread:
- Object spread syntax works with objects, allowing you to copy properties from multiple source objects into a new object.
- Array spread syntax ([...]) works with arrays, allowing you to create a new array by copying elements from an existing array or combining multiple arrays.
Here's an example to illustrate the differences:
In the example above,Object.assign() and object spread syntax achieve similar results by combining properties from multiple source objects into a target object or a new object, respectively. However,Object.assign() modifies the target object, while object spread syntax creates a new object.