"Object.assign". It's easier than you think
Kaziu

Kaziu @kaziusan

About: Frontend Engineer Experience Backend as well ✈ backpacker

Location:
🇵🇱 or 🇯🇵
Joined:
Aug 12, 2019

"Object.assign". It's easier than you think

Publish Date: Sep 22 '22
0 0

💎 What is Object.assign

normally it is used when merge multiple objects

const target = {city: 'japan', capital: 'tokyo'}
const source = {food: 'sushi', history: 'samurai'}

const result = Object.assign(target, source)

console.log(target)
/**
{
 city: 'japan', 
 capital: 'tokyo',
 food: 'sushi',
 history: 'samurai'
}
**/

console.log(source)
// {food: 'sushi', history: 'samurai'}

console.log(result)
/**
{
 city: 'japan', 
 capital: 'tokyo',
 food: 'sushi',
 history: 'samurai'
}
**/
Enter fullscreen mode Exit fullscreen mode

Image description

💎 Object.assign in real life

Contrary to this way of merge, according to my experience, it's often used when wants to copy object

let animal = {name: 'pikachu', type: 'kawaii'}
let copy_animal = Object.assign({}, animal)

console.log(copy_animal)
// {name: 'pikachu', type: 'kawaii'}
Enter fullscreen mode Exit fullscreen mode

🔥 Warning (reference)

Now give you a quiz, is this true or false ??

animal === copy_animal
Enter fullscreen mode Exit fullscreen mode




The answer is false
▼ proof
Image description

▼ There is my other article, which explains about it.

🔥 Warning2 (shallow copy)

let animal = {name: {first: 'pikachu', last: 'honda'}, type: 'kawaii'}
copy_animal = Object.assign({}, animal)

// change value
copy_animal.type = 'dirty'

console.log(animal)
// {name: {first: 'pikachu', last: 'honda'}, type: 'kawaii'}
// ⭐ still pikachu is kawaii !!
Enter fullscreen mode Exit fullscreen mode

Because these objects are on different references

BUT

// change value of second hierarchy 
copy_animal.name.last = 'suzuki'

console.log(animal)
// {name: {first: 'pikachu', last: 'suzuki'}, type: 'kawaii'}
// ⭐ changed 'honda' => 'suzuki' !!!!!!!!!!!
Enter fullscreen mode Exit fullscreen mode

😠 How this result come ?? You said these objects are on different references !!

Yup, but actually this is only 1 hierarchy of object, over 2 hierarchy objects are on same reference and this is called Shallow copy

Yup Object.assign is shallow copy

▼ just log
Image description

💎 Spread operator

By the way spread operator is the same as Object.assign

let animal = {name: 'pikachu', type: 'kawaii'}
let copy_animal = {...animal}

console.log(copy_animal)
// {name: 'pikachu', type: 'kawaii'}
Enter fullscreen mode Exit fullscreen mode

But also shallow copy !!!!!

Comments 0 total

    Add comment