JavaScript Destructing assignment

JavaScript Destructing assignment

2023-06-09
3 min read

Destructing assignment

The Destructing assignment syntax is an expression which unpacks values from Array or Object.

Destructing assignment with Array

js
const a = [1, 2, 3, 4, 5]
const [ num1, num2, num3, num4, num5 ] = a // 1, 2, 3, 4, 5
const [ num1, num2, num3 ] = a // 1, 2, 3
const [ num1, num2, ...others ] = a // 1, 2, [3, 4, 5]
const [ num1 = 9, num2  ] = a // 1, 2
let [ num1 = 9, num2  ] = a // 1, 2
num1 = 9 // num1 is 9
const [ num1, , num3 ] = a // 1, ,3
  • You don't have to unpack all elements in Array.
  • You can unpack leftover elements in array with ....
  • If you would like to reassign destructed variable, you should use let or var.
  • Elements can be ignored with extra comma.

Destructing assignment with Object

js
const box = { x: 10, y: 20, name: 'abc' }
const { x, y, name } = box // 10, 20 , "abc"
const { x, y } = box // 10, 20
const { name, ...others } = box // "abc", {x: 10, y: 20} 
const { name = 'new name', ...others } = box // "abc", {x: 10, y: 20} 
let { name = 'new name', ...others } = box // "abc", {x: 10, y: 20}
name = 'new name' // name is "new name"
const { name, x, y, otherName = 'other' } = box // "abc", 10, 20, "other"
const { name: title } = box // title will be "abc"
  • You don't have to unpack all properties in Object.
  • You can unpack leftover properties in Object with ....
  • If you would like to reassign destructed variable, you should use let or var.
  • Default value is allowed
  • You can change the name of key

Advanced

Let's see how to use destructing assignment along with some examples.

split() function

js
const [firstName, lastName] = 'Arthur Morgan'.split(' ')
let person = {}
[person.firstName, person.lastName] = 'Arthur Morgan'.split(' ')

The split() function in String returns string array cut by parameter

.entries() function in Object

js
let person = {
  name: 'John',
  age: 20
}

for (let [key, value] of Object.entries(user)) {
  console.log(`${key}:${value}`) // name: "John", age: 20
}

Swap variables

js
const a = [1, 2]
console.log(a) // 1, 2
;([ a[0], a[1] ] = [ a[1], a[0] ]) 
console.log(a) // 2, 1
js
let a = 'A'
let b = 'B'
console.log(a, b) // "A", "B"
[a, b] = [b, a]
console.log(a, b) // "B", "A"

the Destructing assigment helps to swap the variables easily.

Function parameter

js
function makeBox({name, width = 20, height = 40}) {}
makeBox({name: 'box 1'})
makeBox({name: 'box 1', width: 200})
makeBox({name: 'box 1', width: 200, height: 300})

Parameter will be set to default value if parameter is not passed.

Nested destructing

js
let box = {
  size: {
    width: 10,
    height: 20
  },
  name: 'Super box'
}
let { name, size } = box
let { name, size: { width, height } } = box

You can use destructing assignemnt in nested Object

Ref

Free open source project made by Youngjin