DEV Community

Cover image for Destructuring in JavaScript
Dalton Saffe
Dalton Saffe

Posted on

Destructuring in JavaScript

Hi! This is a brief introduction to destructuring objects & arrays for developers learning modern JavaScript syntax.

Destructuring is simply a way of extracting & assigning values within objects and arrays to variables. It was standardized by the ECMAScript committee in 2015 for the ES6 release of JavaScript. Destructuring is one of the key ES6 features that will enable developers to trim down verbose syntax and compose modern & legible JavaScript programs.

Objects in JavaScript are initialized and structured like so:

const obj = {
 firstName: 'Gaby', 
 lastName: 'Perez'
 }
Enter fullscreen mode Exit fullscreen mode

Before ES6 one would extract values into variables one by one:

const firstName = obj.firstName
const lastName = obj.lastName
console.log(lastName) // 'Perez'
Enter fullscreen mode Exit fullscreen mode

Now with destructuring the variable assignment:

const { firstName, lastName } = obj
console.log(lastName) // 'Perez'
Enter fullscreen mode Exit fullscreen mode

We now have two variables assigned to their respective values from one line of code. Destructuring is a clear & concise way to declare only the variables you need and associate them with a value within the same line. When using destructuring assignments, remember that the variable name and key name should correspond so the program knows which value it needs to access.

The same extraction pattern applies to arrays in JavaScript. Instead of keys, the variables are declared relative to the index position within the array.

const [ fifty, lol ] = [50, 82]
console.log(lol) // 82
Enter fullscreen mode Exit fullscreen mode

The destructuring assignment pattern shines when dealing with accessing values within nested object structures.

const student = {
  name: 'Ray Lo',
    subjects: {
      math: 'B+',
      science: 'A',
    },
  }

const { math, science } = student.subjects

console.log(science) // 'A'
Enter fullscreen mode Exit fullscreen mode

Within the destructuring assignment there’s the target on the left side of the equal sign and the source on the right. This distinction is fundamental to illustrating the next few concepts of this assignment style.

source-target-img

Elision

When dealing with arrays it’s possible to skip values with commas in the target so you can access the values you need within an assignment.

This technique is known as elision which is defined as the omission of a sound or syllable when speaking. My favorite example of elision is "y'all". Back to JavaScript though.

const arr = ['hey', 'hello', 'sup', destructuring is cool];
const [greet, , , message] = arr
console.log(message) // 'destructuring is cool'
Enter fullscreen mode Exit fullscreen mode

Default Values

If it’s possible that the value in your object may return as undefined one may assign default values within the target to avoid bugs from popping up in the program.

const { a = 5, b = 12 } = { a : 200 }
console.log(a) // 200
console.log(b) // 12
Enter fullscreen mode Exit fullscreen mode

Reassignment

It’s also possible to reassign the names of variables within the destructuring target itself. This can be useful for making your variables more semantic for later usage in your program.

const obj = { greeting: 'HEY', wait: 'HOLD UP' }
const { greeting : sup, wait : chill } = obj
console.log(sup) // 'HEY'
console.log(chill) // 'HOLD UP'
Enter fullscreen mode Exit fullscreen mode

Nested Access

Building off the reassignment syntax examined above is the idea of nested access. This pattern is useful for accessing deeply nested objects that contain separate objects that you’d like to extract values from. Absorbing this idea will help keep your code DRY.

The key difference here is that in the variable after the colon in the target we are wrapping the variable on the right with another pair of braces to access the value stored within. Since that variable name corresponds to an object’s key nested within our parent object we are able to layer the destructuring syntax within itself and access the nested values we need.

const nestedObj = {
  students:{
    autumn:{
      graduated: 1322
    }, 
    winter:{ 
      total: 1337
    }
  }
}

const { autumn: {graduated}, winter: {total} } = nestedObj.students

console.log(graduated, '/////', total)

> 1322 '/////' 1337
Enter fullscreen mode Exit fullscreen mode

Summary

Destructuring is a powerful assignment syntax to make succinct variable declarations and applying this concept in programs will enable one to write elegant, modern JavaScript.

Latest comments (1)

Collapse
 
talesmgodois profile image
talesmgodois

Nice =)