Shallow and deep copy in javascript
Hey there, people of the internet.
Today, we’re diving into the intriguing world of copying objects in JavaScript. Now, I know what you’re thinking: “This is nothing new,” right?
You’re absolutely right. We’ve all experienced situations where copying variables in JavaScript behaves differently depending on whether they’re primitives or objects. For instance, if we have let a = 4 and let b = a, changing a to 5 won’t affect b, which remains 4.
But what about let a = {name: ‘Alex’, age: 25} and let b = a, then modifying a.age to 27 and checking console.log(b)? Surprise! It’s {name: ‘Alex’, age: 27} instead of {name: ‘Alex’, age: 25}. 🤯, right?
Well, the key lies in JavaScript’s behaviour: it copies primitives by value and objects by reference. Now, let’s break down object copying into its two main types: shallow and deep.
Shallow Copy
In a shallow copy, only the top-level properties and primitives get duplicated without their references. This might seem clear-cut until we encounter object properties. These are copied by reference, meaning the original and its copy still share a connection.
Achieving a shallow copy can be done by:
Using the Spread Operator
An efficient way to craft a new object resembling the original. Be cautious with nested structures.
Using the Assign Operator
- The
Object.assign()
method, like the spread operator, enables shallow copying, ideal for merging objects.
To understand the peculiarities of shallow copying, consider the following:
The “address” property, being an object, gets copied by reference, thus sharing data between the original and the copy. This introduces us to the necessity of deep copying.
Deep Copy
Deep copying ensures that every object is copied without references, eliminating issues encountered in shallow copying. Here are methods for deep copying:
Using JSON.parse and JSON.stringify
This powerful combination facilitates deep copies of objects. Due to its popularity, the V8 engine has optimized JSON.parse() for speed. However, be wary of its limitations: circular objects throw errors, and methods within the original objects are disregarded.
Using the Structured Clone Algorithm
Previously hidden from developers, the structuredClone() function, part of the HTML spec, is now accessible. Unlike the JSON methods, it can handle cyclical data structures, supports many data types, and is both more robust and often quicker. Still, it has caveats: class instances return plain objects (losing the prototype chain), and functions within objects are discarded. For details check the MDN article.
Using Lodash
For objects with methods, the deep clone feature in Lodash is an excellent choice. Lodash, an open-source toolkit, offers numerous utility functions driven by functional programming principles.
Well, that's a wrap. In summary, JavaScript’s toolbox for object copying is vast, each with its unique strengths and challenges. Knowing when to use which tool is crucial. By learning about these object-copying techniques, we can easily navigate the complex landscape of JavaScript.
Cheers!
A person on the internet.
Source:
Thanks for reading! If you enjoyed this story, please click the 👏 button and share to help others find it! Also, Feel free to leave a comment 💬 below.