OBJECT
const original = {
name: 'John',
age: 23,
address: {
city: 'Tashkent',
state: 'Oqqorg\'on',
}
}
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
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
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
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