Destructuring

Object Deconstruction

const { id, ...detail } = song;

Use the rest(...) operator to extract some keys individually and the rest of the keys in the object

Loop

for (let {title, artist} of songs) {
  ···
}

Assignment expressions also work in loops

Reassign keys

function printCoordinates({ left: x, top: y }) {
  console.log(`x: ${x}, y: ${y}`)
}

printCoordinates({ left: 25, top: 90 })

This example assigns x to the value of the left key

Function parameters

function greet({ name, greeting }) {
  console.log(`${greeting}, ${name}!`)
}

greet({ name: 'Larry', greeting: 'Ahoy' })

Destructuring of objects and arrays can also be done in function parameters

Defaults

const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores

//Result:
//math === 22, sci === 33, arts === 50

A default value can be assigned when destructuring an array or object

Destructuring assignment

#Arrays

const [first, last] = ['Nikola', 'Tesla']

#Objects

let {title, author} = {
  title: 'The Silkworm',
  author: 'R. Galbraith'
}

Supports matching arrays and objects. See: Destructuring

Comments