JavaScript Destructuring

This YouTube video was created by Steve Griffith.

Destructuringopen in new window is a JavaScript expression that allows the developer to unpack values from arrays or properties from objects into distinct variables.

Destructuring arrays

The destructuring array syntax is a shorthand for assigning array values to individual variables. When destructuring arrays, a set of square brackets ([ ]) will surround the variables.

const colors = ['red', 'green', 'blue']

const [first, second, third] = colors
console.log(first)   // "red"
console.log(second) // "green"
console.log(third)  // "blue"

When unpacking an array, variables can be assigned a default value in the event the array is undefined.

const colors = ['red', 'green', 'blue']

const [first = 'white', second = 'white', third = 'white'] = colors
console.log(first)   // "red"
console.log(second) // "green"
console.log(third)  // "white"

Destructuring objects

Destructuring objects is a shorthand for setting the property values to individual values. When destructuring objects, a set of curly braces ({ }) will surround the variables.

const person = {
  firstName: 'John',
  lastName: 'Smith' 
}

const {firstName, lastName} = person
console.log(`${firstName} ${lastName}`) // John Smith

When unpacking an object, the variable name will typically match the property names, but it is possible to assign the value to a different variable name.

const person = {
  firstName: 'John',
  lastName: 'Smith' 
}

const {firstName: fn, lastName: fn} = person
console.log(`${fn} ${ln}`) // John Smith

When unpacking an object, it is possible to assign a default value to the new variables, in case the unpacked object does not contain the appropriate property.

const numbers = {
  a: 5,
  b: 7
}

const {a: 0, b: 0, c: 0} = numbers
console.log(a)  // 5 
console.log(b)  // 7 
console.log(c)  // 0