The heart of tech is coming to the heart of the Mediterranean. Join TNW in València this March 🇪🇸

This article was published on July 25, 2020

How to write cleaner code with JavaScript

Add clarity and reduce the complexity of your code by destructing your objects and arrays in JavaScript

How to write cleaner code with JavaScript Image by: Unsplash: Caspar Camille Rubin

Destructuring is one of my favorite tools in JavaScript, in simple terms, destructuring allows you to break down a complex structure (like an array or an object) into simpler parts, though there’s a bit more to it than that.

Let’s see it better in an example:

Now, some people have been using this feature for some time, perhaps while building React apps, but they don’t quite understand it, for others it may be the first time. So I’ll guide you from the start so that by the end of the article we’ll have the same level of understanding.

Destructuring objects

In the example above, all the magic happens at the following line:

Now it may seem a bit weird to have those brackets like that on the left side of the assignment, but that’s how we tell JavaScript that we’re destructing an object.

Destructuring on object lets you bind different properties of an object at any depth. Let’s start with an even simpler example:

In the case above, we’re declaring a variable called name which will be initialized from the property with the same name in the object me, so that when we evaluate the value of name we get Juan. This same method can be applied to any depth, to which heading back to our example:

For title and rating it’s exactly the same as we already explained, but in author, things are a bit different. When we get to a property which is either an object or an array, we can choose whether to create a variable author with a reference to the object, or we can do a deep destructuring and get immediate access to the properties of the inner object.

Accessing the object property

Doing a deep or nested destructuring

Wait, what? If I destructed author, why is it not defined? What is going on is actually really simple. When we ask JavaScript to destruct the author object, that binding itself is not created and instead we get access to all the author properties we selected. So please always remember that.

Spread operator (…)

Additionally, we can use the spread operator ... to create an object with all the properties which didn’t get destructed.

If you’re interested in knowing how to do this, check out my previous article on the Spread Operator in JavaScript.

Renaming properties

One great property of destructing is the ability to choose a different name for the variable to the property we are extracting. Let’s look at the following example:

By using : on a property we can provide a new name for it, in our case newName. Then we can access that variable in our code. It’s important to notice that a variable with the original property name in our case name won’t be defined.

Missing properties

So what would happen if we try to destructure a property that is not defined in our object?

In this case, the variable is created with value undefined.

Default values

Expanding on missing properties, it’s possible to assign a default value for when the property does not exist, let’s see some examples of this:

In the example above we demonstrated some examples of assigning default values to our destructions. The default values are only assigned when the property is undefined. If the value of the property is for instance null or a string the default value won’t be assigned, but the actual value of the property.

Destructuring arrays and iterables

We already saw some examples of destructuring objects, but the same can apply to arrays or iterables in general. Let’s start with an example:

The example is self-explanatory when we need to destruct an array we need to use [] instead of {}, and we can map each position of the array with a different variable. But there are some nice tricks too.

Skipping elements

By using the , operator, we can skip some elements from the iterable as follows:

Notice how leaving it empty between , skips the elements. This may be subtle but it has big consequences in the end results. You can also use the spread operator ... as follows:

In this case, z will get all the values after b as an array. Or maybe you have a more specific need, and you want to destruct specific positions in the array, no problem, JavaScript got you covered:

If we destruct an array as if it were an object, we can use the indexes as properties and thus access any position within the array.

Missing properties

As was the case of objects, it’s also possible to set default values for undefined elements in the array. Let’s take a look at some examples:

For destructing arrays, it’s also possible to set default values for undefined  properties, however, it’s not possible to set a default when we have the spread operator ..., which in the case of undefined, will return an empty array.

Swapping variables

This is a fun use case of destructuring, 2 variables can be swapped in one single expression:

Destructuring with computed properties

Until now, any time we wanted to destruct the properties of an object, or the elements of an iterable, we used static keys. If we want dynamic keys (as those stored on a variable) we need to use computed properties.

Here’s an example:

Pretty awesome right! By using a variable between [], we can evaluate its value before doing the assignment, and thus it’s possible to do dynamic destructuring.However, it’s mandatory to provide a name for this new variable.

Destructuring function arguments

Destructing variables can be placed anywhere where we can declare variables. For example by using let, const or var, but it’s also possible to deconstruct in function arguments. Here’s a simple example of the concept:

As you can see, it’s very simple and elegant and uses all the same rules we’ve previously discussed.

Destructuring may seem awkward at the beginning, but once you get used to it, there’s no turning back. It can really help your code be more readable.

This article was originally published on Live Code Stream by Juan Cruz Martinez, founder and publisher of Live Code Stream, entrepreneur, developer, author, speaker, and doer of things. You can follow Juan on Twitter here

Live Code Stream is also available as a free weekly newsletter. Sign up for updates on everything related to programming, AI, and computer science in general.

Also tagged with