DEV Community

Muhammad Asif
Muhammad Asif

Posted on

Shallow Copying in JavaScript using Object Spread Operator

For the longest time, you had to resort to workarounds and libraries to create a deep copy of a JavaScript value.

Copying a value in JavaScript is almost always shallow, as opposed to deep. That means that changes to deeply nested values will be visible in the copy as well as the original.

One way to create a shallow copy in JavaScript using the object spread operator...:

const myOriginal = {
  someProp: "with a string value",
  anotherProp: {
    withAnotherProp: 1,
    andAnotherProp: true
  }
};

const myShallowCopy = {...myOriginal};
Enter fullscreen mode Exit fullscreen mode

Adding or changing a property directly on the shallow copy will only affect the copy, not the original:

myShallowCopy.aNewProp = "a new value";
console.log(myOriginal.aNewProp)
// ^ logs `undefined`
Enter fullscreen mode Exit fullscreen mode

However, adding or changing a deeply nested property affects both the copy and the original:

myShallowCopy.anotherProp.aNewProp = "a new value";
console.log(myOriginal.anotherProp.aNewProp) 
// ^ logs `a new value`
Enter fullscreen mode Exit fullscreen mode

The expression {...myOriginal} iterates over the (enumerable) properties of myOriginal using the Spread Operator. It uses the property name and value, and assigns them one by one to a freshly created, empty object. As such, the resulting object is identical in shape, but with its own copy of the list of properties and values. The values are copied, too, but so-called primitive values are handled differently by the JavaScript value than non-primitive values. To quote MDN:

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods. There are seven primitive data types: string, number, bigint, boolean, undefined, symbol, and null.

MDN — Primitive

Non-primitive values are handled as references, meaning that the act of copying the value is really just copying a reference to the same underlying object, resulting in the shallow copy behavior.

That's it for now. Next article I will write about Deep copies in JavaScript.

Wrapping Up

I hope you enjoyed the article, if yes then don't forget to press ❤️ and Subscribe. You can also bookmark it for later use. It was fun to create this article and If you have any queries or suggestions don't hesitate to drop them. See you.
You can extend your support by giving me stars on GitHub Profile.😊👇
Github
Portfolio

Support

Buy me a Coffee

Top comments (0)