Understanding Deep vs Shallow Copying in JavaScript
--
JavaScript, like most programming languages, has mechanisms for creating duplicate values or copying information. In this article we’re going to look at two key ways of making JavaScript copies: Deep and Shallow copying.
Copying a variable with a primitive data type like a string or number is fairly straight forward, but it can get a bit complex when it comes to copying iterable objects.
What’s an Iterable Object?
An iterable object is simply anything in JavaScript that can be looped through — objects and arrays are both iterable.
Technically an array in javascript has a datatype of object but we won’t go there in this article.
Here’s an example of a JavaScript object we’ll work with:
const person = {
name: "Jacob Khan",
age: 23,
address: {
street: "123 Main Street",
city: "New York",
state: "NY",
}
};
Shallow Copying
If we wanted to use the spread operator (...
) to copy our person
object. The syntax might look like this:👆
const copiedPerson = { ...person };
Pretty easy, right? Now let’s do some editing. Changing the age
property on our copied object won't affect our original person
data:
copiedPerson.age = 33;
Nice! But what if we change the state
inside the address
property?
copiedPerson.address.state = "CA";
Oops! If you check the original person
object, you'll find that the state
has also updated in the original object.
This is because the spread operator makes a shallow copy of the object, only going one level deep. For nested properties or elements, it merely copies the reference, not the actual nested objects.
The Solution: Deep Copying
Deep copying, as the name suggests, copies an object more thoroughly. It replicates not just the top-level properties, but also duplicates all the lower, nested…