DEV Community

Cover image for Array Destructuring in JS!
Ustariz Enzo
Ustariz Enzo

Posted on • Updated on

Array Destructuring in JS!

Hey fellow creators

Destructuring is a nice way to create some variables from an array or an object! Let's learn how to do it in less than a minute.

If you prefer to watch the video version, it's right here :

1. The syntax.

You have to follow the same syntax every time. For example:

const array = ["#ff0000", "#008000", "#0000ff"];

const [red, green, blue] = array;

console.log(red, green, blue);
Enter fullscreen mode Exit fullscreen mode

If you look in your console, you'll see that each name is linked to its colour:

image of the console

2. You can also give some default values.

You can give some default values, just in case that array is empty:

const array = [];

const [red = "1", green = "2", blue = "3"] = array;

console.log(red, green, blue);
Enter fullscreen mode Exit fullscreen mode

In your console will therefore show "1 2 3".

3. You can also ignore some values!

Remove one colour name from the array but leave the comma:

const array = ["#ff0000", "#008000", "#0000ff"];

const [red = "1", , blue = "3"] = array;

console.log(red, blue);
Enter fullscreen mode Exit fullscreen mode

It'll ignore the second value and simply create a constant for red and blue:

Image of the console showing the two colours

4. Create a constant for all the remaining parts of an array.

const fruits = ["kiwi", "strawberry", "lemon"];

const [first, ...others] = fruits;

console.log(first, others);
Enter fullscreen mode Exit fullscreen mode

It created one constant for the first element and an array of the remaining element named "others" :

Image of the console showing the first constant and then the second one

You now know how destructuring works in Javascript!

Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool

Happy coding!

Enzo.

Discussion (0)