what is destructuring assignment ?
π unpack values from arrays, or properties from objects
π Basic form
const user = {
name: 'kaziu',
age: 87
}
let { name } = user
console.log(name) // "kaziu"
βΌ What if I would change property of name ?
const user = {
name: 'kaziu',
age: 87
}
let { name } = user
name = 'pikachu' // ββ add it
console.log(user) // ββββββββββ
The answer is user.name
shows kaziu
. Changing name
does not have effect to original object
π Explanation
1.
When you assign object, variable name user
allocates somewhere on memory, and has reference of this object
const user = {}
2.
then name
property has its reference
const user = {
name: 'kaziu'
}
3.
Now use destructing assignment
const user = {
name: 'kaziu',
age: 87
}
let { name } = user // ββ Now add it and then ...?
4.
change kaziu
to pikachu
, it doesn't have effect to original object
const user = {
name: 'kaziu',
age: 87
}
let { name } = user
name = 'pikachu'
console.log(user.name) // 'kaziu'
π How about deep hierarchy object ?
const user = {
name: {
first: 'kaziu',
last: 'suzuki'
}
}
let { name } = user
console.log(name) // { first: 'kaziu', last: 'suzuki' }
name.first = 'pikachu'
console.log(user)
// { name: { first: 'pikachu', last: 'suzuki' } }
// ββ original object changes from `kaziu` to `pikachu` !!!
Because over second hierarchy, reference is the same as original object.
By the way, it calls shallow copy
Top comments (0)