Destructuring Objects

This Scrimba screencast was created by Dylan C. Israel.

Basic Usage

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

New Variable Names

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

Default Values

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

See Also

This YouTube video was created by Steve Griffith.