JavaScript - Copying (Shallow vs Deep)

Overview

Estimated time: 10–15 minutes

Copying objects and arrays is a common task. Learn the difference between shallow and deep copies in JavaScript.

Learning Objectives

  • Understand shallow vs deep copy.
  • Use built-in and custom methods for copying data.

Prerequisites

Shallow Copy

const arr = [1, 2, 3];
const arr2 = arr.slice();

Deep Copy

const obj = { a: 1, b: { c: 2 } };
const deep = JSON.parse(JSON.stringify(obj));

Common Pitfalls

  • Deep copy with JSON loses functions and special types.

Summary

Choose the right copy method for your data structure and use case.