A Javascript shallow copy means that the primitive datatype value of the new variable is disconnected from the original variable and the compositive datatype value of the new variable is connected from the original variable.
You can create shallow copy through the below methods.
1) Object.assign(target_object,source_object);
2) through spread operator
1) Copy through Object.assign() method
Syntax:-
var new_object=Object.assign({},object)
Example:-
Suppose, You have an employee object and copy object through Object.assign() into new object new_employee
let employee = {
firstName: 'John',
lastName: 'Taylor',
address: {
city: 'Mumbai',
state: 'maharashtra',
country: 'India'
}
};
let new_employee = Object.assign({}, employee);
new_employee.firstName = 'Rom'; // disconnected
new_employee.address.city = 'New Delhi'; // connected
new_employee.address.state = 'Delhi'; // connected
console.log("newEmployee:-",new_employee);
console.log("oldEmployee:-"employee);
firstName: “Rom”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}
oldEmployee:- {
firstName: “John”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}
2) Copy through spread operator
Syntax:-
var new_object={...Object};
Example:-
Suppose, You have an employee object and copy object through spread operator (…) into new object new_employee
let employee = {
firstName: 'John',
lastName: 'Taylor',
address: {
city: 'Mumbai',
state: 'maharashtra',
country: 'India'
}
};
let new_employee = {...employee};
new_employee.firstName = 'Rom'; // disconnected
new_employee.address.city = 'New Delhi'; // connected
new_employee.address.state = 'Delhi'; // connected
console.log("newEmployee:-",new_employee);
console.log("oldEmployee:-"employee);
firstName: “Rom”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}
oldEmployee:- {
firstName: “John”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}
Javascript Object shallow copy – Interview Questions
Q 1: What is a shallow copy in JavaScript?
Q 2: How do you create a shallow copy?
Q 3: What happens to nested objects in a shallow copy?
Q 4: Is the spread operator a shallow copy?
Q 5: When should a shallow copy be used?
Javascript Object shallow copy – Objective Questions (MCQs)
Q1. A shallow copy copies ______.
Q2. Which method creates a shallow copy?
Q3. Spread operator {...obj} creates a ______ copy.
Q4. Changes in nested objects of a shallow copy will affect the ______.
Q5. Shallow copy works well for objects without ______.