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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more