DEV Community

Shirley
Shirley

Posted on

Difference between Shallow Copy and Deep Copy

“Tell me, what is the difference between a shallow copy and a deep copy? And how can you make a deep copy of an object?”

This was a question I got in an interview for a full stack web developer position. I have never heard of the terms “shallow copy” and “deep copy” back then. But it’s absolutely essential that web developers and software engineers understand the difference between a shallow copy and a deep copy. Interviewers will mostly definitely ask you how you can make a deep copy. Here is what you need to know.

First, you need to understand that primitive values are passed by value, while objects and arrays are passed by reference. What do I mean by that? When you pass by value, you create a copy of the original value. When you pass by reference, you make an alias to the original. Objects are stored in memory using a reference value. The reference value is an address in memory where the object is located. When you make a shallow copy of an object, you copy the reference, not the object itself. The actual object isn’t copied.

So a shallow copy copies the reference, and a deep copy copies the actual value of the object. Here are four ways you can make a shallow copy:

  1. Object assign() method. You can use Object.assign() to copy over all enumerable properties of an object to a new object. For example:
const obj = {firstName: "John", lastName:"Smith"};
const newObj = Object.assign({}, obj);
Enter fullscreen mode Exit fullscreen mode

In this example, the newObj will contain the same properties and values as the original obj.

  1. Spread operator. You can duplicate an array or an object by using the spread operator.
const arr = [1, 2, 3, 4];
const newArr = [...arr];
// newArr = [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode
  1. Slice method. You can clone an array by slicing it.
const arr = ["a", "b", "c"];
const newArr = arr.slice();
// newArr = ["a", "b", "c"]
Enter fullscreen mode Exit fullscreen mode
  1. Array.from() method.
const arr = [1, 2, 3];
const newArr = Array.from(arr);
Enter fullscreen mode Exit fullscreen mode

Here are ways to make a deep copy:

  1. Lodash. After importing Lodash, you can use their cloneDeep() method to make a deep copy.
import _ from "lodash"
const obj = {firstName:"John", lastName:"Smith"};
const newObj = _.cloneDeep(obj);
Enter fullscreen mode Exit fullscreen mode
  1. Ramda.
import R from "ramda"
const obj = {firstName:"John", lastName:"Smith"};
const newObj = R.clone(obj);
Enter fullscreen mode Exit fullscreen mode
  1. JSON.parse(JSON.stringify())
const obj = {firstName:"John", lastName:"Smith"};
const newObj = JSON.parse(JSON.stringify(obj));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)