3 Practical Uses of Object Destructuring in JavaScript

Write cleaner code using these destructuring patterns

By now you are probably quite familiar with destructuring in JavaScript! It came to us back in 2015 in the ES6 Specification, but if you need to brush up on it, Mozilla has a great in-depth article on how it works.

Knowing how destructuring works is not the same as knowing how to use it, however. Here are three destructuring patterns you can use to make your code cleaner, more robust, and more readable!

1. Named Function Arguments

Named arguments are an alternative way to handle function parameters rather than by position. Instead of ordering your arguments in the same order as the function signature, you simply specify the argument by name. For example, in Python:

As you can see, the order of the arguments does not matter — you just specify them by name. The benefits of named arguments vs. positional are:

  1. You can leave off one or more parameters when calling the function
  2. Order does not matter when passing in arguments.
  3. More readable code when calling a function that might exist elsewhere

While true named arguments do not exist in JavaScript, we can use a destructuring pattern to achieve all 3 of the same benefits. Here is the same code as above, but in JavaScript:

This patterns hits all of our goals for named arguments. We were able to leave off the argument c, the order does not matter, and we assign our argument by referencing them by name. This is all made possible by object destructuring.

2. Cleanly Parse a Server Response

Often we only care about the data block or even one specific value in the data block of a server response. If that is the case, you can use destructuring to only grab that value while ignoring a lot of the other things a server typically sends back. Here is an example:

This pattern allows you to pull out values from an object as your arguments are being parsed. You also get to set up defaults for free! Which brings us to the third pattern…

3. Setting Default Values During Assignment

A common case when assigning variables or constants is to have a default value if some other value doesn’t currently exist in the scope.

Prior to destructuring, you could do something like this to achieve that desired behavior:

// old way of setting up default values
var nightMode = userSettings.nightMode || false

But this requires an individual line of code for each assignment. With destructuring, you can take care of all of your assignments and their defaults all at once:

This destructuring pattern can be applied to setting up state in your React components!