DEV Community

Falcão
Falcão

Posted on

Array Destructuring in Javascript, do you know what it is?

Recently I was programming in one of my projects and when I innocently went to get the first value of an array as every good programmer does const value = array[0], my Eslint immediately complained and told me to use something called Array Destructuring, I was very confused because I had never heard of such a technique.

If you, like me, don't know what that is, today we will see everything about this powerful syntax that makes manipulating arrays much more enjoyable.

Table of contents

What the linter wanted me to know

Imagine that we want to extract information from an array, usually what we do is something like the following:

let introduction = ["I", "want" , "to", "play", "minecraft"];
let person = phrase[0];
let game = phrase[4];

console.log(person); //"I"
console.log(game); //"minecraft"
Enter fullscreen mode Exit fullscreen mode

However, in Javascript ES6, the new Array Destructuring method was introduced to extract information from an array, let's see its syntax using the same example:

let phrase = ["I", "want" , "to", "play", "minecraft"];
let [person, desire] = phrase;

console.log(person); //"I"
console.log(desire); //"want"
Enter fullscreen mode Exit fullscreen mode

We can also do it like this:

let [person, desire] = ["I", "want" , "to", "play", "minecraft"];

console.log(person); //"I"
console.log(desire); //"want"
Enter fullscreen mode Exit fullscreen mode

Or like this:

let person, desire;
[person, desire] = ["I", "want" , "to", "play", "minecraft"];

console.log(person); //"I"
console.log(desire); //"want"
Enter fullscreen mode Exit fullscreen mode

Note that the 3 ways presented have the same result, and as expected, the variables have their values assigned from left to right, so the first variable receives the first value of the array, the second the second and so on.

Skipping values

Maybe now you are thinking that I deceived you, because I said that I would show the same example, but here we are taking the first two values, instead of the first and the last, let's see how to do that:

let [person,,,,game] = ["I", "want" , "to", "play", "minecraft"];

console.log(person); //"I"
console.log(game); //"minecraft"
Enter fullscreen mode Exit fullscreen mode

What happened here?

Note that instead of 1 comma, here we have 4, this is how we do to "skip" values in destructuring, we have the normal comma and three additional ones, which indicate that we want to skip three values, so we can replicate the original behavior of getting the first and last value.

This special comma can also be placed at the beginning of the array, indicating that we want to skip the first value:

let [,desire,,,game] = ["I", "want" , "to", "play", "minecraft"];

console.log(desire); //"want"
console.log(game); //"minecraft"
Enter fullscreen mode Exit fullscreen mode

The comma operator also allows us to do something very funny, skip all items in an array:

// :)
let [,,,,,] = ["I", "want" , "to", "play", "minecraft"];
Enter fullscreen mode Exit fullscreen mode

Assigning the rest of the array

Everything we've seen here is very cool, but choosing and skipping values from the array is unlikely to happen in the real world, and if we want to take the first variable and put the rest in a specific variable?

let [person, ...rest] = ["I", "want" , "to", "play", "minecraft"];

console.log(person); //"I"
console.log(rest); //["want", "to", "play", "minecraft"]
Enter fullscreen mode Exit fullscreen mode

Arrays and functions

This technique is especially useful when we are using functions that return an array, so we can extract the values directly:

function getArray() {
    return ["I", "want" , "to", "play", "minecraft"];
}
let [person, desire] = getArray();

console.log(person); //"I"
console.log(desire); //"want"
Enter fullscreen mode Exit fullscreen mode

Using default values

Another interesting property, we can use initial values for our variables, just like in functions:

let [person = "I", game = "minecraft"] = ["me"];

console.log(person); //"me"
console.log(game); //"minecraft"
Enter fullscreen mode Exit fullscreen mode

In the example above, the game variable used the initial value we gave it since there was no other value in the array.

If you are wondering what happens if we put more variables on the left side than values on the right side, without using default values, in this case the remaining variables simply receive undefined:

let [person, desire] = ["I"];

console.log(person); //"I"
console.log(desire); //undefined
Enter fullscreen mode Exit fullscreen mode

Passing the job interview

Now a curiosity:

let a = 3;
let b = 6;

[a, b] = [b, a];

console.log(a); //6
console.log(b); //3
Enter fullscreen mode Exit fullscreen mode

And that's it! Now thanks to this text you can answer if they ask you how to swap the value of two variables without using a third one :D

Conclusion

If you used React or React Native before, Array Destructuring is exactly what is happening when you use useState:

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

Thank you for reading and I hope you have learned something new today or reinforced what you already knew! I certainly learned a lot to write this article, if you want to read more about destructuring in general, I recommend the mozilla documentation.

Top comments (1)

Collapse
 
falcao_g profile image
Falcão • Edited

Additionally, it's also possible to use destructuring on function parameters:

function doSomething([ person, action ]) {
    console.log(`${person} ${action}`);
}

fazAlgo([ 'You' ]); // You undefined
fazAlgo([ 'You', 'want' ]) // You want
Enter fullscreen mode Exit fullscreen mode

Or with default values:

function doSomething([ person = 'Me', action = 'nothing' ]) {
    console.log(`${person} ${action}`);
}

fazAlgo([ 'You' ]); // You nothing
fazAlgo([ 'You', 'want' ]) // You want
Enter fullscreen mode Exit fullscreen mode

Thanks for user kht on tabnews for this addition