Preparation
πŸ’‘ ⏐ JavaScript Questions
10. Shallow and Deep copy

Shallow and Deep Copy

When working with objects and arrays in JavaScript, it's important to understand the concepts of shallow and deep copy, as they determine how data is copied and shared between variables.

Shallow Copy:

A shallow copy of an object or array creates a new object or array, but it only copies the references to the original values. This means that if the original object contains nested objects or arrays, the shallow copy will still reference the same nested objects or arrays. Therefore, changes made to the nested objects or arrays in the shallow copy will also affect the original object.

  • Shallow Copy of Objects:

    let originalObject = { name: 'Alice', age: 30, hobbies: ['reading', 'painting'] }
    let shallowCopy = Object.assign({}, originalObject)
     
    shallowCopy.age = 31 // Modifying the shallow copy
    shallowCopy.hobbies.push('gardening') // Modifying the nested array
     
    console.log(originalObject.age) // Output: 30 (unchanged)
    console.log(originalObject.hobbies) // Output: ["reading", "painting", "gardening"] (modified)
  • Shallow Copy of Arrays:

    let originalArray = [1, 2, [3, 4]]
    let shallowCopy = originalArray.slice()
     
    shallowCopy[0] = 5 // Modifying the shallow copy
    shallowCopy[2].push(5) // Modifying the nested array
     
    console.log(originalArray) // Output: [1, 2, [3, 4, 5]] (modified)

Deep Copy:

A deep copy, on the other hand, creates a completely new copy of the original object or array, including all nested objects or arrays. This ensures that changes made to the copied object or array do not affect the original one, and vice versa.

  • Deep Copy of Objects:

    let originalObject = { name: 'Alice', age: 30, hobbies: ['reading', 'painting'] }
    let deepCopy = JSON.parse(JSON.stringify(originalObject))
     
    deepCopy.age = 31 // Modifying the deep copy
    deepCopy.hobbies.push('gardening') // Modifying the nested array
     
    console.log(originalObject.age) // Output: 30 (unchanged)
    console.log(originalObject.hobbies) // Output: ["reading", "painting"] (unchanged)
  • Deep Copy of Arrays:

    let originalArray = [1, 2, [3, 4]]
    let deepCopy = JSON.parse(JSON.stringify(originalArray))
     
    deepCopy[0] = 5 // Modifying the deep copy
    deepCopy[2].push(5) // Modifying the nested array
     
    console.log(originalArray) // Output: [1, 2, [3, 4]] (unchanged)

Considerations:

  • Performance: Deep copying can be slower and consume more memory compared to shallow copying, especially for large and complex objects or arrays.
  • Circular References: Deep copying using JSON.stringify() and JSON.parse() cannot handle circular references and will throw an error.

Understanding shallow and deep copy is crucial when working with complex data structures in JavaScript, as it ensures that data is handled and manipulated correctly without unexpected side effects.