Awesome Javascript — Destructuring assignment
Tags: web, dev, es6, javascript
Published: 2019-03-02 17:31:14

---
title: Awesome Javascript — Destructuring assignment
published: true
tags: web,dev,es6,javascript
canonical_url: https://medium.com/@codingsam/awesome-javascript-destructuring-assignment-55fd2e9d3dc4
---

### Awesome Javascript — Destructuring assignment

![](https://cdn-images-1.medium.com/max/750/1*jC6q6xNDHlNS5_mVT3Qawg.png)

Javascript is becoming more and more a really cool language. Why? Because of all the features introduced in [ES6](http://es6-features.org/) (ECMAScript 6 aka ECMAScript 2015) and all the other more advanced versions. ECMAScript is just the standardized specification of Javascript. Some browsers already support it. However, it is usually not safe to rely on that, because there is no guarantee that any browser will support the complete specification. The best thing to do is to use a transpiler, that converts your ES6 code to ES5, which for sure will run in any browser. [_Babel_](https://babeljs.io/) is a well known transpiler that you can integrate in most used build tools, such as, [_webpack_](https://webpack.js.org/) or [_gulp_](https://gulpjs.com/)_._

I had worked with a lot of Javascript in a web development project in one of my previous jobs. I mean… a lot! Try to work in a frontend without any framework (no React, angular or anything else!). So, as you can imagine, I got really familiar with Javascript, but it was ES5.

Since a couple months ago, I have to deal with a lot of ES6 in my full time job. It has a lot of cool features. That’s why I decided to start a new series of posts about the features I learned about (and still learning)!

This post is about the _destructuring assignment_, which I think it is a clean way to deal with objects and arrays.

> Basically, it is just an awesome way to get values from arrays and objects.

Let’s see how it works!

### Array destructuring

You can get some values from a given array and give them any name you want. For instance, let’s say you have an array of numbers, _[1, 2, 3, 5, 8, 13, 21]_ and you want to store the first two indexes in separate variables. In “normal” Javascript you would do something like:

{% gist https://gist.github.com/samfcmc/f6337b8a324d0052b8953c4d5eb300c0 %}

The variable x and y contain the indexes 0 and 1, respectively. The rest, contains all other remaining numbers _[3, 5, 8, 13, 21]_.

Now, let’s do it the ES6 way!

{% gist https://gist.github.com/samfcmc/e7798160bf9fdebb2accffef3d5be790 %}

This does the same as the previous code, but it looks much better. You get the first two positions from the array in variables _x_ and _y_. The remaining values are stored in the _rest_ constant. If you don’t know about what the “_const_” keyword means, don’t worry, it is something from ES6, it’s used to define a value that cannot be reassigned.

### Object destructuring

In ES5, to get values from objects, you just simply need to know which keys have the values you want and type something like _myObject.myKey_. Let’s say, you have an object that describes a person with the properties: name, age, gender, address and phone number. If you want to extract the name and age properties, you just need to simply do:

{% gist https://gist.github.com/samfcmc/7be6d6c00970e256933f161f81b284ed %}

If you are using ES6 you can do it like this:

{% gist https://gist.github.com/samfcmc/6c72fe9eb11f915751f335b2058fb65e %}

You just extracted some keys from the object and also got another object with the remaining keys (gender, address and phone). Remember the weird “…” thing from the array destructuring? This “…rest” does the same, but in this case, it is an object.

I hope you get the idea, but let me give you an example to help you to get a better feeling about how awesome is this!

### Example

Let’s say, you are implementing a 2D game in Javascript, for instance Bomberman. Who does not know about this one, right? Right??? :)

![](https://cdn-images-1.medium.com/max/256/1*__Qjq_ioJpGPq8h4phyyng.png)<figcaption>Bomberman game</figcaption>

You already have the following function:

- _getPosition_: returns the bomberman’s current position, in a pair of coordinates (_x_ and _y_), in the 2D grid where all the action is happening

There are two ways of defining a position, using an array or an object. In the array implementation, the zero and one indexes are the _x_ and _y_ coordinates, respectively. Using an object, this will have the _x_ and _y_ keys with the coordinates values. To use this _getPosition_ function, you can use the destructuring assignment to get your code a lot cleaner than without using it.

Now, you need to implement a function:

- _getDistance_: returns the distance (in _x_ and _y_ axis) between two positions.

For instance, if you have the following positions:

- _position0 = {x: 2, y: 4}_
- _position1 = {x: 5, y: 3}_

The distance between them should be _{x: 3, y: -1}_ because, _5-2=3_ and 3–4=-1.

#### Using an array

Choosing the array implementation, if you call the _getPosition_ function, you will get an array where the index zero is the _x_ coordinate and the index one is the _y _value.

Let’s see how we can use this function, using the _destructuring assignment_:

{% gist https://gist.github.com/samfcmc/133950e830eb8aa3894f5cbbb2dae3ad %}

What if our _getPosition_ function does return an _undefined_ coordinate for some reason? You can set default values, so your code does not crash!

{% gist https://gist.github.com/samfcmc/e25f4167029a9ffcef0c2087a4189df1 %}

Remember the _getDistance_ function introduced in the example? Let’s define it assuming our positions are represented using an array:

{% gist https://gist.github.com/samfcmc/dd6746fd43e8409519f1d1eba1c209a3 %}

It is already a really looking good code, but you can remove some lines if you do the destructuring stuff in the function’s arguments list!

{% gist https://gist.github.com/samfcmc/8421f838d1eff66ae1021d2d9e47c2f4 %}

Is this too fast? Let’s break it down because there are a lot of stuff going on here :)

- _[x1 = 0, y1 = 0]:_ this thing in the function’s header, basically means you expect an array with two positions. You are naming its indexes zero and one to _x1_ and _y1_, respectively. In case that the array has less than two positions, or is completely empty, those _x1_ and _y1_ values become zero. **Have in mind that you can pass an empty array but you cannot omit it, otherwise, you will get an error**!
- _const [xDistance, yDistance] = getDistance(position1, position2)_: here you are just calling the _getDistance_ function that returns an array. Instead of storing that array in a variable (or a constant as I am doing in this example), you are assigning the zero and one indexes in two constants named _xDistance_ and _yDistance,_ respectively.

#### Using an object

The same _getPosition_ exercise could be implemented using an _object_ instead of an _array_. Let’s write an _object_ version!

{% gist https://gist.github.com/samfcmc/4ed81ff11f87cecaf6c74c8a9147eb7f %}

And you also can set _default_ values, like we did in the array version!

{% gist https://gist.github.com/samfcmc/05a1a9200794393ca38f83987aed6133 %}

Awesome right? :)

Now, let’s create the _getDistance_ function:

{% gist https://gist.github.com/samfcmc/0307e33e3db636af3d091b762e50c1d9 %}

I am using the destructuring assignment here with default values. Also, I am renaming its keys, so I can distinguish between the _x_ and _y_ from _position1_ (_x1_ and _y2_) and _x_ and _y_ from _position2_ (_x2_ and _y2_).

Is it possible to do better? Yes! Let’s do it!

{% gist https://gist.github.com/samfcmc/9ccb1a124e9f89fd1840a8f853459d8c %}

You can save some lines if you already know that your function arguments are objects with some given keys. Like I have done in the array implementation, here I can also move the destructuring part to the function’s header! Let’s break it down:

- _{ x: x1 = 0, y: y2 = 0 }_: Basically this means that you expect an object, as the function’s first argument, with two keys _x_ and y. However, you are naming those keys _x1_ and _y1_ (this is useful because the function expects two objects with the same keys). **Have in mind that you are not changing anything in the object passed to the function (renaming the keys, {x: x1, y: y2}, does not change the keys names in the object).** Also, if this object does not have a defined value for the _x_ key, the value zero (_x: x1 = 0_) is used instead. The same is true for the _y_ key.
- _const { x: xDistance, y: yDistance } = getDistance(position1, position2)_: This calls the getDistance function. You could just put the result in a constant, but as you can see, you can destructure that object if you already know which keys you are expecting. The “_x: Distance”_ part gets the _x_ value from the returned object and renames it to _xDistance_.

### Conclusion

If you already work with Javascript ES6 (and more advanced standards), it’s very likely that you already know this destructuring assignment and you love Javascript.

Anyway, have in mind that, in order to use this feature, you should transpile your code to ES5. Otherwise, there is a small chance that your code will not run in some browsers. As mentioned in the beginning of this post, go check _Babel_. I didn’t explained anything about how to setup a transpiler because I just wanted to focus on one particular feature instead of writing a really big post.

I hope you liked it and learned something. Share this, especially, with your developer friends that hate Javascript :)

Let me know what you think and follow me for more cool content about dev stuff :)

- [Coding Sam](https://medium.com/u/58cf94a36c97) @ Medium
- [codingsam @ Twitter](https://twitter.com/codingsam01)
- [codingsam01 @ Instagram](https://www.instagram.com/codingsam01)