Destructuring, the easiest way

Reading Time: 4 minutes

In the last days, I have been working on a project with ‘React’, and every single day I have come across something called ‘destructuring’. The javascript community always talks about it, but, What is destructuring? What is it used for? Where can we use it? In this blogpost, I will be talking about this topic which nowadays is very useful among ‘the javascript’s community’.  So. take some notes because we will make some exercises, here we go!

What is destructuring?

Destructuring is a feature that was incorporated to the ES6 release. Before that, there wasn’t a corresponding mechanism for destructuring elements, and for that reason, the term has become well known, and nowadays very useful.

Destructuring is extracting multiple values from stored data in objects or arrays. In order to understand its meaning, consider...

function foo() {

  return [1,2,3];
}

let buz = foo(),

    a = buz[0], b = buz[1], c = buz[2];

console.log(a, b, c); // 1 2 3

If you notice, we created a manual assignment of the values in the array that foo() returns to individual variables a, b and c, in order to do so, we need the buz variable.

Similarly, we can do the following with objects:

function bar() {
  return {
    x: 4,
    y: 5,
    z: 6
  };
}

let buz = bar(),
    x = buz.x, y = buz.y, z = buz.z;

console.log(x, y, z); // 4 5 6

The buz.x property value is assigned to the x variable, just like buz.y to y and buz.z to z.

ES6 adds syntax aimed at destructuring, specifically ‘arrays destructuring’ and ‘object destructuring’. This syntax eliminates the need for using the buz variable in the previous snippets, making them much cleaner. Consider...

let [a, b, c] = foo();

let { x, y, z } = bar();

console.log(a, b, c); // 1 2 3

console.log(x, y, z); // 4 5 6

You probably are more accustomed to seeing syntax like [a, b, c] on the right side of a = assignment, as the value being assigned.

Destructuring symmetrically flips that pattern, so that [a, b, c] on the left side of the = assignment is treated as a “pattern” for decomposing the right side array value into separated variable assignments.

Array destructuring

Array destructuring (works for all iterable values):

let array = [1,2,3];

let [first, second, third] = array;

console.log(second); // 2

When it comes to arrays, you can conveniently skip over elements which you don’t care about:

let [,,a, b] = [1,2,3,4,5];

console.log(a); // 3

console.log(b); // 4

You can choose the last elements that an array returns evaluating them to one value:

let [a,b, ...c] = [1,2,3,4,5,6,7];

console.log(c); // [ 3, 4, 5, 6, 7 ]

 ## Object destructuring

You can destructure an object by using the key’s value as the name of the variable to destructure it, consider...

let employee = { firstName: "Sam", lastName: "Belmor" };

let { firstName, lastName } = employee;

console.log(lastName); // 'Belmor'

Sometimes the names of the keys are not so explicit, and we want to change them. You can do it by following the next steps…

let coordinates = { x: 24.6, y: 92.8, z: 73.4};

let { x: coordX, y: coordY, z: coordZ } = coordinates;

console.log(coordX); // 24.6

Now, if you try to print the variables x, it will throw a:

ReferenceError: x is not defined

This error occurs because the variables x, y, and z do not exist anymore. Now, you can only access with the new name that you already established.

Nested destructuring

Destructuring can also be used to assign values in nested elements, and by doing that, the access to these values becomes way easier.

let  users = ['Samantha', ['Ayrton', 'Dzoara', 'Yasser'], 'Maritzel'];

let  [a, [b, c, d], f] = users;

console.log(c);  // 'Dzoara'

console.log(f); // 'Maritzel'

When destructuring nested objects, consider:

const user = {

  personalInfo: {

    userName: 'Samantha',

    lastName: 'Belmor',

    school: {

      name: 'Tec de Colima',

      grade: '5 sem'
    };
  };
};

Using the previous example, we are going to destructure 'userName, lastName, and school. In order to accomplish this, we have to do the following:

let { personalInfo: { userName, lastName, school } } = user;

console.log(userName); // 'Samantha'

console.log(lastName); // 'Belmor'

console.log(school); // { name: 'Tec de Colima', grade: '5 sem' }

Now we want to destructure the school name and grade. We can do it like this:

let { personalInfo: { userName, lastName, school: { name, grade } } } = user;

console.log(name); // 'Tec de Colima'

console.log(grade); // '5 sem'

Also, we can skip the variables ‘userName’ and ‘lastName; if we are not using them anymore:

let { personalInfo: { school: { name, grade } } } = user;

Note

For a better understanding of all the problems, I added some extras spaces in some of them, and it is worth mentioning that it’s very important to follow these rules. It is really easy to make mistakes while using JavaScript since it is such a dynamic and loosely-typed language. A way to improve your code could be using a very powerful tool called ESLint. ESLint allows developers to discover problems with their JavaScript code without executing it. The ELSins was created mainly to allow developers to create their own listing rules. ESLint is designed to have all rules completely pluggable. The default rules are written just like any plugin rules would be.

Conclusion

I hope that these previous examples help you understand a little bit more about this topic, and you can get a better idea about destructuring’s flexibility and power in JavaScript.
This functionality can be applied both to arrays and objects with an equal or different number of elements in each term. It is not necessary to occupy all the values within the object or array, you can filter the values you need and use them where and when required.

We are Hiring

In MagmaLabs we are always looking for talented and passionate professionals. If you want to join us don’t hesitate to visit our Careers page.

 

0 Shares:
You May Also Like