DEV Community

_Khojiakbar_
_Khojiakbar_

Posted on • Edited on

1

Deep vs Shallow cloning 2

OBJECT

const original = {
    name: 'John',
    age: 23,
    address: {
        city: 'Tashkent',
        state: 'Oqqorg\'on',
    }
}
Enter fullscreen mode Exit fullscreen mode

SPREAD:

// Spread => Shallow copying
let copiedObj = {...original}
copiedObj.name = 'Alice'
copiedObj.address.city = 'Samarkand';

console.log(copiedObj.name)
console.log(original.name)

console.log(original.address.city)
console.log(copiedObj.address.city)

// Alice
// John
// Samarkand
// Samarkand
Enter fullscreen mode Exit fullscreen mode

Equal(=):

// = / very shallow copying it is even copying non-nested properties
let copiedObj = original;
copiedObj.name = 'Alice'
copiedObj.address.city = 'Samarkand'

console.log(original.name)
console.log(copiedObj.name)
console.log(original.address.city)
console.log(copiedObj.address.city)

// Alice
// Alice
// Samarkand
// Samarkand
Enter fullscreen mode Exit fullscreen mode

Object.assign():

// Object.assign() => Shallow copy
let copiedObj = Object.assign({}, original)
copiedObj.name = 'Alice';
copiedObj.address.city = 'Samarkand'
console.log(original.name)
console.log(copiedObj.name)
console.log(original.address.city)
console.log(copiedObj.address.city)

// John
// Alice
// Samarkand
// Samarkand
Enter fullscreen mode Exit fullscreen mode

JSON:

// JSON => Deep copy
let copiedObj = JSON.parse(JSON.stringify(original))
copiedObj.name = 'Alice'
copiedObj.address.city = 'Samarkand'

console.log(original.name)
console.log(copiedObj.name)
console.log(original.address.city)
console.log(copiedObj.address.city)

// John
// Alice
// Tashkent
// Samarkand
Enter fullscreen mode Exit fullscreen mode

Please leave your appreciation by commenting on this post!

Of course, only if it was helpful.

Okay, let's go.

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay