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…