Skip to main content
JavaScriptResourcesWeb Dev

Deep and shallow copying in JavaScript – part 1

By August 15, 2020July 17th, 2022One Comment
Deep and shallow copy in JavaScript

Copying objects with shallow and deep copies

Primitive values such as strings, and numbers are copied by value, whereas objects are copied by reference. What do we mean by this? The following code example will explain this practically:

let num1 = 10;
let num2 = num1;
num1 = 6;
console.log(num2); //10

The value of num1 which is the number 10 is assigned to the variable num2. Which is why even after we change the value of num1 to the number 6, the value of num2 remains the same. It’s because we copied by value of num1 to num2 before re-assignment of variable num1 to 6.
What then does copy by reference mean? When we copy by reference, the memory address of an object is shared with another object. For example:

let num1 = {
let num2 = num1;
num1.amount = 6;

The following is logged:

Object {
  amount: 6

Since the memory address of the two objects are the same, when we change the value of
the num1 amount key from the number 10 to 6, we are changing the value at the memory location. Therefore, the value of the amount key in the num2 object will also be the number 6, since it refers to the same memory address.
When copy over objects, we cannot simply just use the assignment = operator. There are
two ways of copying objects:
1. Shallow copying
2. Deep copying

Which gets us to the next point, what do these two terms mean?

Shallow copy

In a shallow copy, a new object is created which has the exact values as the source object.
Primitive values are copied by value whereas if a field is of a reference type (example an
array or another object) then the reference/memory address is copied over to the newly
created target object. In a shallow copy, the source object and target object share the
same memory address.


Deep copy

In a deep copy, all the values (primitive and reference types) are duplicated into a source
object and allocated new memory locations. Therefore, the memory address of the target
and source objects is different. Changing the source object after a deep copy will not
affect the target object.



An important note to keep in mind is that in a deep copy, the source and target objects have different memory addresses and are not connected. Whereas, in a shallow copy the source and target objects share a memory address.

One Comment

Leave a Reply