Destructuring Assignments in JavaScript.

Destructuring Assignments in JavaScript.

The destructuring assignment is a relatively new JavaScript expression that comes with ES6, that makes it possible to unpack values from arrays or properties form objects into variables. In other words it implements a kind of compound declaration and assignment. In a destructuring assignment the value on the right-hand side of the assignment operator is a structured value (an array or an object) and on the left hand side we have variables using a syntax that mimic array and object literal syntax. In a destructuring assignment there is an unpacking of values where either one or more values from the right hand side of the equal sign is stored into the variables named on the left. Let us take a look at an example at this point.

let [a,b] = [1,2]; // Same as let a=1, b=2
[a,b] = [a+1,b+1]; // Same as a = a + 1, b = b + 1
[a,b] = [b,a]; // Swap the value of the two variables
[a,b] // => [3,2]: the incremented and swapped
values

Let’s look at a more complex example and see how how the destructuring assignments can help simplify functions that return arrays of values. Our function takes a value of coordinates and converts them to [r,theta] polar coordinates and vice versa.

// Convert [x,y] coordinates to [r,theta] polar coordinates
function toPolar(x, y) {
return [Math.sqrt(x*x+y*y), Math.atan2(y,x)];
}

// Convert polar to Cartesian coordinates
function toCartesian(r, theta) {
return [r*Math.cos(theta), r*Math.sin(theta)];
}
let [r,theta] = toPolar(1.0, 1.0); // r == Math.sqrt(2);
theta == Math.PI/4
let [x,y] = toCartesian(r,theta); // [x, y] == [1.0, 1,0]

From our examples above where so far we have had equal values on both sides of the assignment operators i.e. the number of variables on the left equals the number of array elements on the right but this does not have to be the case as values on the left do not have to match the values on the right. When we have extra variables on the left, they are set to undefined and extra values on the right are simply ignored. Another interesting feature is that the variables on the left can include extra commas to skip certain values on the right.

let [x,y] = [1]; // x == 1; y == undefined
[x,y] = [1,2,3]; // x == 1; y == 2
[,x,,y] = [1,2,3,4]; // x == 2; y == 4

When destructuring an array it is possible to just want to pass only a few items of the array into few of the variables on the left and collect the the remaining unpacked items into a single variable. We can use this using three dots (…) which is also used to represent the spread and rest operators.

let [x, ...y] = [1,2,3,4]; // y == [2,3,4]

You might want to check out the rest and spread operator, this article really gives a nice break down and you will see your newly discovered tool (…) at work.

Destructuring Assignment is not only restricted to array and objects but any iterable object can be used on the right hand side of the assignment. In other words an object that can be used with (a for/of loop) can also be destructured.

let [first, ...rest] = "Hello"; // first == "H"; rest ==
["e","l","l","o"]

Remember when I mentioned above that the variables on the left mimic an array or object literal syntax, we can apply this knowledge if we want to destruct a nested array. In this example notice how we make the variables look like a nested array.

let [a, [b, c]] = [1, [2,2.5], 3]; // a == 1; b == 2; c ==
2.5

All the examples so far have been dealing with arrays lets take a look at an example with objects.

I encourage you to please type out the examples and see the results for yourself

let continents = {A: "Africa", E: "Europe", SA: "South America"}
let {A, E, SA} = continents; // A==Africa, E==Europe, SA==South America

This example might not be really clear but I will explain it further with another example that applies the same logic during destructuring. This next example copies global functions of the Math object into variables, which might simplify code that does a lot of trigonometry.

// Same as const sin=Math.sin, cos=Math.cos, tan=Math.tan
const {sin, cos, tan} = Math;

What is going on in the code example above is that certain properties of the Maths object are being destructured based on the name of the variables on the left hand side. It is good to note that the Math object has many properties and those that are not named are simply ignored like stated above and if the left hand side of the assignment operator had included a variable whose name was not a property of Math, that variable would simply be assigned undefined. So in the example before this we saw that the continent object had the following properties (A, E and SA ) and we give this names to our variable. This syntax is quite easy and recommended but there is another way of doing this which might not be quite clear at first sight. So I will give an example of such scenario.

// Same as const cosine = Math.cos, tangent = Math.tan;
const { cos: cosine, tan: tangent } = Math;

In this syntax Each of the identifiers on the lefthand side of an object destructuring assignment can also be a colon-separated pair of identifiers, where the first is the name of the property whose value is to be assigned and the second is the name of the variable to assign it to.

Another complex example I will like to use to round up this blog post is destructuring with an array of objects. Which sometimes might be too complex to be useful. In this example keep in mind the logic we used in the last example above.

let points = [{x: 1, y: 2}, {x: 3, y: 4}]; // An array of
two point objects
let [{x: x1, y: y1}, {x: x2, y: y2}] = points; //
destructured into 4 variables.
(x1 === 1 && y1 === 2 && x2 === 3 && y2 === 4) // => true

This concludes the end of this blog post. Thanks for your time. Do like, share and drop a comment below if you find this post useful. If you plan on learning React you will find this destructuring assignments very useful.