Data structures: Destructuring arrays

Data structures: Destructuring arrays

Part 1: A guide to destructure arrays

馃殌 Before we start

You know that I'm a beginner and I'm studying hard to be a web developer. I'm focusing on JavaScript and I want to start a series called: Data structures.

I'm following along the Jonas Schmedtmann JavaScript course and I got to the Data Structures section, it's very technical and if you don't have a good motivation, it can overwhelm you.

There are a lot of blog posts and videos about this topic, but as a way to learn, I want to share my notes about this section, it'll help me to understand it better if I can explain it well and I hope it helps you to understand this topic clear, and if I make a mistake, please don't hesitate to leave a comment and correct it, I love feedback.

So, let's start.

馃し What's a Data structure?

Every programming language has a data structure, it's how all the information can be organized depending on your needs. With that organization, you can access, modify, create or delete data.

If you need to solve some problems using a programming language, first of all, you need to gather the information and organize it, depending on the programming language, you can take different approaches.

In JavaScript, there are a lot of ways to organize data, (check MDN to see the full list), but the most common ones are arrays and objects, which are the ones that we are going to focus on in this series.

馃し Why do I need to destructure?

Destructuring is to unpack values in an array or object properties and pack them into different variables. In other words, making a complex data structure to a more simple one.

Sometimes information is not received in the way we want it or we need it, so we have to extract that data and convert it into a different variable.

For example: I have an array of car models:

const cars = ['toyota', 'nissan', 'honda', 'hyundai', 'kia'];

But I need to get the model name because I'll assign an owner list to each car model.

As a beginner this could be a possible solution:

const toyota = cars[0];
const nissan = cars[1];
const honda = cars[2];
const hyundai = cars[3];
const kia = cars[4];

馃檵 How to destructure arrays?

The code above is too repetitive, don't you think? So here's when destructuring comes to play. The way we will do it is by adding square brackets in the name of the variable like this:

const [toyota, nissan, honda, hyundai, kia] = cars;
console.log(toyota, nissan, honda, hyundai, kia); 
// 'toyota' 'nissan' 'honda' 'hyundai' 'kia'

In that simple way, we saved 4 lines of code. Translating that a little bit means that every element on the array will be created as a new variable. The name of the variable will be taken by looking at the order.

Toyota will be 'toyota' because it's the first value in the array cars[0]. You could pick a different name if you want, but since we want to make this as clearly as possible, I suggest you do it with the same name to not get confused, but if you're very comfortable with your code, you can also do it like this:

const [carNum1, carNum2, carNum3, carNum4, carNum5] = cars;
console.log(carNum1, carNum2, carNum3, carNum4, carNum5); 
// 'toyota' 'nissan' 'honda' 'hyundai' 'kia'

I definitely wouldn't recommend you that, but it's just to clarify the point that a new variable has been created as carNum1 and it will take the first element in the array that is 'toyota'

Destructuring data won't modify the array, it'll remain intact because you're creating new ones.

鉁 The order matters

Destructuring arrays will only take the elements in the array, based on the order, however, if there are more elements than variables, it'll take just the variables you have stated.

Let's see it in code with the cars variable:

const [toyota, nissan] = cars;
console.log(toyota, nissan, honda);
// Uncaught ReferenceError: honda is not defined

Why does that happen? It's because we're not creating a variable for honda, just for the first two elements.

鉁 Skipping variables

What about if I need to take just the first element toyota and the third one honda. You can skip elements by leaving a blank space separated by commas when declaring the variables, like this:

const [toyota,  , honda] = cars;
console.log(toyota, honda);
// 'toyota' 'honda'

鉁 Switching variables

We saw that the order is very important, but what about if I want to save the elements in the new array but sorted differently.

A beginner solution would be creating a temporary variable to have the switched element.

const array = ['main','secondary'];
let [main,secondary] = array

const temp = main;
main = secondary;
secondary = temp;

console.log(main, secondary);
// 'secondary', 'main'

In the end, that solves the problem, the only thing is that we have to use a temporary variable, to not modify the original value, but again, it's too much code, and also you can be a little bit confused by the way you're assigning variables (I'd be confused too).

Destructuring helps us to solve the switching part in an easier way:

[main, secondary] = [secondary, main] ;
console.log(main, secondary);
// 'secondary' 'main'

鉁 Destructuring from a function

You can be more creative by getting the values from a function. Imagine I want to pick a normal car and a luxury car model for the week, let's see this example:

const normalCars = ['toyota', 'nissan', 'honda', 'hyundai', 'kia'];
const luxuryCars = ['mercedes','lexus','bwm','ferrari','lamborghini'];

function pickACar(normal, luxury){
    return [normalCars[normal],luxuryCars[luxury]];

const [weekday,weekends] = pickACar(1,2);
// 'nissan' 'bwm'

We went to advanced here, but it's a cool example. So, what I'm doing is to have two arrays, one is normalCars and the other one is luxuryCars, I'm creating a function that accepts as parameters one normal car and one luxury car, they will be numbers because the function will return the position of the arrays.

So far, we're not destructuring, but if we execute the function and save it in variables like [weekday,weekends], the return values will be stored on those variables.

鉁 Nested arrays

Believe me, I understand that overwhelmed feeling when things are nested, because as a beginner, you have to go to the child element to understand its parent and so on, but it's a matter of getting used to it and studying them more.

In destructuring, nesting is not an exception. So, we can do it for arrays that have nested data:

const nestedArr = [1,2,[3,4]];
const [individual, ,nested] = nestedArr;
console.log(individual, nested);
// 1 [3,4]

As you noticed, it shows the first value in the individual variable, we skipped the second one and the nested variable is the nested array nestedArr. But what about if we want to include all the numbers from the nested array. We have to destructure the nested array too.

const [individual, ,[nested1, nested2]] = nestedArr;
console.log(individual, nested1,nested2);
// 1 3 4

Some advanced developers have another solution for that, but we're gonna leave it for another blog post, but I wanted to show you that it's possible to do it in that way.

鉁 Default values in destructuring

There are some times in which we don't know the number of elements that an array has, or we don't know the type of data that it could have.

const [a, b, c] = [1, 2];
// 1 2 undefined

That's why we can create a default value for our variables, so if the variable doesn't find any element in the array, it will show the value set by default:

const [a = 5, b = 5, c = 5] = [1, 2];
// 1 2 5

We define defaults by adding the equal sign next to the variable, the same as we do with parameters in functions. It's very useful when we use data from a third -arty provider or API.

Thank you for reading, see you in the next part of this series.