What is shallow copy and deep copy in Javascript - Free Web Development || UI Development || React JS || Angular

Latest

Free Web Development ||Free UI Development || React JS || HTML5 || CSS3 || JavaScript || Angular Learn Web Development || Frontend Developer || Full Stack Developer

1 / 3
Welcome to Shravan Ghanchi

Tuesday, April 8, 2025

What is shallow copy and deep copy in Javascript

In JavaScript, deep copy and shallow copy refer to how objects (or arrays) are duplicated. They determine whether the copied object shares the same references as the original object or creates entirely new ones.

1. Shallow Copy:  A shallow copy creates a new object, but copies only the first level of properties. If the properties of the original object are references (like objects or arrays), these references are copied, not the actual values. This means changes to nested objects in the copy will affect the original object.

Shallow Copy In JavaScript

2. Deep Copy: A deep copy creates a completely independent copy of the entire object, including nested objects. Changes in the copy won't affect the original, and vice versa.

Difference:

Shallow Copy: Copies only the first level and shares references for nested objects. 

Deep Copy: Copies everything, creating independent nested objects. 

Ways to Create Shallow Copies 

1. Using the spread operator (...): 


2. Using Object.assign:





Ways to Create Deep Copies 1. 


1. Using JSON methods: 

javascript const deepCopy = JSON.parse(JSON.stringify(original));


 2. Using structuredClone (modern method):

 
javascript const deepCopy = structuredClone(original); // Works for complex objects 

3. Using libraries (e.g., Lodash's _.cloneDeep): 

javascript const deepCopy = _.cloneDeep(original);

No comments:

Post a Comment

Snow
Forest
Mountains
Snow
Forest
Mountains