WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Intermediate · question 36 of 100

Can you explain the difference between a shallow copy and a deep copy of an object in JavaScript?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

In JavaScript, objects are references to memory locations, rather than actual values. When you create a copy of an object, you can create either a shallow copy or a deep copy, depending on how the copy is made.

A shallow copy of an object creates a new object with the same properties and values as the original object, but the properties that are objects themselves are still references to the same memory locations as the original object. In other words, the top-level properties are copied, but the nested objects are not.

Here’s an example of how to create a shallow copy of an object:

    const obj1 = { a: 1, b: { c: 2 } };
    const obj2 = Object.assign({}, obj1);
    
    obj1.b.c = 3;
    
    console.log(obj2.b.c); // Outputs 3

In this example, obj1 is an object with a property b that is another object. The Object.assign() method is used to create a shallow copy of obj1 and assign it to obj2. When the b.c property of obj1 is changed, it also changes in the shallow copy obj2.

A deep copy of an object creates a new object with the same properties and values as the original object, but all of the properties that are objects themselves are also deep-copied, so that they refer to new memory locations. In other words, both the top-level properties and the nested objects are copied.

Here’s an example of how to create a deep copy of an object:

    const obj1 = { a: 1, b: { c: 2 } };
    const obj2 = JSON.parse(JSON.stringify(obj1));
    
    obj1.b.c = 3;
    
    console.log(obj2.b.c); // Outputs 2

In this example, JSON.stringify() is used to convert obj1 to a JSON string, and then JSON.parse() is used to parse the JSON string into a new object. This creates a deep copy of obj1, because the nested object b is also copied. When the b.c property of obj1 is changed, it does not affect the deep copy obj2.

In summary, a shallow copy of an object only creates a new reference to the same memory location as the original object, while a deep copy creates a new object with new references to all of the nested objects. Depending on your needs, you may want to use either a shallow or a deep copy of an object in your code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics