MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Deep Copy vs Shallow Copy0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
5.1map, filter, reduce5.2find, some, every5.3Array.from & Array.of5.4Deep Copy vs Shallow Copy
HomeTutorialsJavaScript for IntermediateDeep Copy vs Shallow Copy
Object.keys, Object.values, Object.entries

Deep Copy vs Shallow Copy

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

In JavaScript, primitive values (numbers, strings, booleans, symbols, null, undefined) are copied by value, whereas objects (including arrays, functions, and plain objects) are referenced by memory address. Misunderstanding the boundary between shallow copies and deep copies is one of the most frequent causes of state mutation bugs.


1. References vs. Copies

1const userA = { name: 'Alice', score: 95 };
2const userB = userA; // COPIES REFERENCE ONLY!
3 
4userB.score = 100;
5console.log(userA.score); // 100! userA was mutated!

2. Shallow Copy: Methods and Limitations

A shallow copy creates a new outer object or array, but any nested objects or arrays inside it are still shared references.

Methods for Shallow Copying

  1. 1
    Object Spread Operator: { ...source }
  2. 2
    Array Spread Operator: [ ...sourceArray ]
  3. 3
    Object.assign(): Object.assign({}, source)
  4. 4
    Array.prototype.slice(): sourceArray.slice()
1const original = {
2 title: 'Mastering JavaScript',
3 author: { name: 'Sarah', country: 'Canada' } // Nested Object
4};
5 
6// Shallow copy
7const copy = { ...original };
8 
9copy.title = 'Advanced JavaScript'; // Safe! Only copy.title changes.
10copy.author.country = 'Germany'; // DANGER! Mutates BOTH original and copy!
11 
12console.log(original.author.country); // 'Germany' (Shared reference!)

3. Deep Copying: Modern structuredClone()

A deep copy recursively duplicates every level of nested objects and arrays, ensuring complete isolation in memory.

The Modern Standard: structuredClone()

Introduced natively in modern JavaScript (Node.js 17+ and all modern browsers):

1const order = {
2 id: 'ORD-9812',
3 items: [{ sku: 'KB-01', qty: 2 }],
4 createdAt: new Date()
5};
6 
7// TRUE DEEP COPY:
8const deepClonedOrder = structuredClone(order);
9 
10deepClonedOrder.items[0].qty = 5;
11console.log(order.items[0].qty); // 2! Original is completely untouched!
12console.log(deepClonedOrder.createdAt instanceof Date); // true! Preserves Date objects!

Features of structuredClone():

  • Handles nested objects and arrays to any depth.
  • Supports cyclic references (objects referencing themselves).
  • Preserves Date, RegExp, Map, Set, and ArrayBuffer instances.
  • Limitation: Does not clone functions or DOM nodes (throws DataCloneError).

4. The Legacy JSON Hack (and its gotchas)

1const legacyCopy = JSON.parse(JSON.stringify(original));

Critical Pitfalls of JSON.parse(JSON.stringify()):

  • Discards functions and methods.
  • Converts Date objects into ISO strings.
  • Converts NaN and Infinity to null.
  • Throws errors on circular references.
  • Strips undefined values and Symbol keys.

5. Summary Cheat Sheet

TechniqueCopy DepthPreserves Dates/RegExp?Handles Circular Refs?Clones Functions?
Object.assign({}, obj)ShallowYes (references)N/ACopies reference
{ ...obj }ShallowYes (references)N/ACopies reference
JSON.parse(JSON.stringify())DeepNo (converts to string)Throws ErrorDrops functions
structuredClone(obj)DeepYesYesThrows Error

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What happens when you modify a nested object property inside a shallow copy created with {...original}?
Question 2
What native modern JavaScript API provides true deep cloning out of the box?
Question 3
What is a major limitation of using JSON.parse(JSON.stringify(obj)) to clone objects?
Question 4
Which of the following creates a shallow copy of an array?
Question 5
What error occurs if you pass an object containing a function to structuredClone()?
Next Lesson

Object.keys, Object.values, Object.entries

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Array.from & Array.ofObject.keys, Object.values, Object.entries

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext