DEV Community

Kaziu
Kaziu

Posted on

Destructuring assignment in javascript

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"
Enter fullscreen mode Exit fullscreen mode

β–Ό What if I would change property of name ?

const user = {
  name: 'kaziu',
  age: 87
}

let { name } = user

name = 'pikachu' // ⭐⭐ add it
console.log(user) // ❓❓❓❓❓❓❓❓❓❓
Enter fullscreen mode Exit fullscreen mode

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 = {}
Enter fullscreen mode Exit fullscreen mode

Image description

2.

then name property has its reference

const user = {
  name: 'kaziu'
}
Enter fullscreen mode Exit fullscreen mode

Image description

3.

Now use destructing assignment

const user = {
  name: 'kaziu',
  age: 87
}

let { name } = user // ⭐⭐ Now add it and then ...?
Enter fullscreen mode Exit fullscreen mode

Image description

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'
Enter fullscreen mode Exit fullscreen mode

Image description

πŸ’Ž 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` !!!
Enter fullscreen mode Exit fullscreen mode

Because over second hierarchy, reference is the same as original object.
By the way, it calls shallow copy

Image description

Top comments (0)