Javascript Object deep copying means that the value of the new variable is disconnected from the original variable.
You can create the deep copying through JSON.parse method with JSON.stringify
Syntax:-
let new_object_name = JSON.parse(JSON.stringify(object_name));
Example:- Suppose you have employee object and copy object through JSON.parse() method with JSON.stringify into new_employee object then you change the firstName, city and state in new_employee object then it will not connected to old employee object.
let employee = {
firstName: 'John',
lastName: 'Taylor',
address: {
city: 'Mumbai',
state: 'Maharashtra',
country: 'India'
}
};
let new_employee = JSON.parse(JSON.stringify(employee));
new_employee.firstName = 'Rom'; // disconnected
new_employee.address.city = 'New Delhi'; // disconnected
new_employee.address.state = 'Delhi'; // disconnected
console.log(new_employee);
console.log(employee);
firstName: “Rom”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}
oldEmployee:- {
firstName: “John”
lastName: “Taylor”
address: {city: “Mumbai”, state: “Maharashtra”, country: “India”}
}
Javascript Object Deep copy – Interview Questions
Q 1: What is a deep copy?
Ans: A deep copy creates an independent copy of all nested objects.
Q 2: How to create a deep copy?
Ans: JSON.parse(JSON.stringify(obj)).
Q 3: What is the limitation of the JSON method?
Ans: It cannot copy functions or undefined values.
Q 4: Does deep copy share references?
Ans: No.
Q 5: When is deep copy required?
Ans: When nested data must be completely independent.
Javascript Object Deep copy – Objective Questions (MCQs)
Q1. Deep copy duplicates ______.
Q2. Which method creates a deep copy (with limitations)?
Q3. Which modern method creates a true deep copy?
Q4. Deep copy prevents ______ between original and copied objects.
Q5. JSON-based deep copy does NOT support ______.