DEV Community

Kaziu
Kaziu

Posted on

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

πŸ’Ž 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 !!!!!

Top comments (0)