3 Practical Uses of Object Destructuring in JavaScript

Last updated 2 years ago by Jim Rottinger


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:

``` def sum(a=1,b=2,c=3): return a+b+c

sum(b=5,a=10) ```

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:

You can leave off one or more parameters when calling the function Order does not matter when passing in arguments. 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:

``` function sum({a = 1, b = 2, c = 3}) { return a + b + c }

sum({b: 10, a: 5}) // 5 + 10 + 3 = 18 ```

Read full Article