JavaScript Interview Question #35

What is a shallow copy, and how is it different from a deep copy?

Objects, Arrays & Core Data Handling Junior Beginner

Quick Interview Answer

A shallow copy creates a new top-level object or array but keeps references to nested objects. Therefore, modifying a nested object through the copy can also affect the original.

Detailed Explanation

A shallow copy creates a new top-level object or array but keeps references to nested objects. Therefore, modifying a nested object through the copy can also affect the original.

A deep copy recursively duplicates supported nested values. Modern JavaScript provides structuredClone for many structured data types. JSON serialization is sometimes used for simple data but has important limitations and should not be treated as a universal deep-cloning solution.

Code Example

const original = {
    name: "Asif",
    address: { city: "Multan" }
};

const shallow = { ...original };
shallow.address.city = "Lahore";

console.log(original.address.city); // Lahore

const deep = structuredClone(original);
deep.address.city = "Karachi";

console.log(original.address.city); // Lahore