DEV Community

Coding Sam
Coding Sam

Posted on • Originally published at Medium on

Awesome Javascript — Destructuring assignment

Awesome Javascript — Destructuring assignment

Javascript is becoming more and more a really cool language. Why? Because of all the features introduced in ES6 (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 is a well known transpiler that you can integrate in most used build tools, such as, webpack or gulp.

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:

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!

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:

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

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??? :)

Bomberman game

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:

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

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

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!

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!

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

Awesome right? :)

Now, let’s create the getDistance function:

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!

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 :)

Top comments (0)