Published on

Understanding Shallow Copy vs Deep Copy in JavaScript

Authors
  • Name
    Ripal & Zalak
    Twitter

Introduction

When working with objects and arrays in JavaScript, copying data can be tricky. Depending on your approach, you may end up with a shallow copy or a deep copy, each having significant implications on how data is manipulated. In this blog, we will explain the differences between shallow copy and deep copy, and how to use them effectively.

What is a Shallow Copy?

A shallow copy creates a new object or array, but it only copies references to the values of nested objects or arrays, rather than copying the nested objects themselves.

Example

const original = { a: 1, b: { c: 2 } }
const shallowCopy = { ...original }

shallowCopy.b.c = 42
console.log(original.b.c) // 42

Key Takeaway

Changes to nested objects in the shallow copy affect the original object, as they share the same reference.

What is a Deep Copy?

A deep copy creates a new object or array, recursively copying all nested objects or arrays so they are independent of the original.

Example

const original = { a: 1, b: { c: 2 } }
const deepCopy = JSON.parse(JSON.stringify(original))

deepCopy.b.c = 42
console.log(original.b.c) // 2

Key Takeaway

Changes to nested objects in a deep copy do not affect the original object, as they are completely independent.

How to Create Shallow Copies

Using the Spread Operator

const arr = [1, 2, 3]
const shallowCopy = [...arr]

Using Object.assign

const obj = { a: 1, b: 2 }
const shallowCopy = Object.assign({}, obj)

How to Create Deep Copies

Using JSON

const deepCopy = JSON.parse(JSON.stringify(obj))

Using a Utility Library

Libraries like Lodash offer robust deep copy methods.

const _ = require('lodash')
const deepCopy = _.cloneDeep(obj)

Writing a Custom Recursive Function

For complex cases:

function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }
  const copy = Array.isArray(obj) ? [] : {}
  for (const key in obj) {
    copy[key] = deepClone(obj[key])
  }
  return copy
}

Key Differences at a Glance

FeatureShallow CopyDeep Copy
Nested ObjectsShares referencesCreates independent copies
PerformanceFasterSlower
Use CasesSimple objects or arraysComplex or deeply nested structures

When to Use Each

  • Shallow Copy: When working with flat objects or arrays where nested changes are not a concern.
  • Deep Copy: When working with deeply nested structures or when you need complete independence from the original object.

Conclusion

Understanding the difference between shallow and deep copies is crucial for managing data effectively in JavaScript. By choosing the right approach for your needs, you can avoid unintended side effects and write more robust code.