Saturday, May 18, 2024
HomeJavaScriptDeep copy and shallow copy in JavaScript | by Pravin M |...

Deep copy and shallow copy in JavaScript | by Pravin M | Feb, 2024


Deep copy and shallow copy in JavaScript

Supply:- Deep copy and shallow copy in JavaScript

For extra questions and solutions go to our web site at Frontend Interview Questions

Shallow Copy:

A shallow copy of an object refers to a brand new object that’s created, duplicating the construction of the unique object. This duplicate accommodates references to the identical youngster objects as the unique however not the precise youngster objects themselves. In different phrases, whereas the top-level properties of the thing are copied, any nested objects or arrays throughout the unique object are nonetheless referenced by each the unique and the shallow copy.

To raised perceive the idea of a shallow copy, take into account an instance utilizing JavaScript:


const originalObject = {
prop1: 'Hey',
prop2: {
nestedProp1: 'World'
}
};

// Making a shallow copy
const shallowCopy = Object.assign({}, originalObject);

// Modifying the shallow copy
shallowCopy.prop1 = 'Hola';
shallowCopy.prop2.nestedProp1 = 'Mundo';

console.log(originalObject); // { prop1: 'Hey', prop2: { nestedProp1: 'Mundo' } }
console.log(shallowCopy); // { prop1: 'Hola', prop2: { nestedProp1: 'Mundo' } }

On this instance, we create a shallow copy of originalObject utilizing Object.assign(). Each originalObject and shallowCopy have their top-level properties (like prop1) independently modified with out affecting one another. Nonetheless, after we modify a nested property (like nestedProp1) inside shallowCopy, it additionally displays the identical change in originalObject. It’s because each objects reference the identical nested object

Deep cloning/copying an object in JavaScript means creating a brand new object that’s an impartial copy of the unique object, together with all nested objects and arrays. There are a number of approaches to deep cloning an object in JavaScript. Listed here are three frequent strategies:

  1. Utilizing `JSON.parse()` and `JSON.stringify()`:

const originalObject = {
title:'check title',
addr:{
metropolis:'check metropolis',
state:'check state'
}
}
const clonedObject = JSON.parse(JSON.stringify(originalObject)); // will returned clone of given object

This technique works by changing the unique object to a JSON string utilizing `JSON.stringify()`, after which parsing the JSON string again into a brand new object utilizing `JSON.parse()`. This creates a deep copy of the unique object, nevertheless it has limitations. It is going to discard any perform properties, undefined properties, or properties with round references.

2. Utilizing a recursive perform:


perform deepClone(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}

const clonedObj = Array.isArray(obj) ? [] : {};

for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clonedObj[key] = deepClone(obj[key]);
}
}

return clonedObj;
}

const originalObject = {
title:'check title',
addr:{
metropolis:'check metropolis',
state:'check state'
}
}
const clonedObject = deepClone(originalObject); // will returned clone of given object

let arr=[1,2,3,[4,5 ,[6,7]]];
const clonedArray = deepClone(arr); // will returned clone of given Array

This technique entails making a recursive perform `deepClone()` that traverses the thing and creates a deep copy by recursively cloning nested objects and arrays. It handles round references and capabilities correctly. Nonetheless, be cautious when utilizing this technique with very massive or deeply nested objects, as it may possibly impression efficiency.

Understand that deep cloning an object can have efficiency implications, particularly for big or advanced objects. Select the strategy that fits your wants, making an allowance for efficiency issues and the particular necessities of your use case.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments