DEV Community

Cover image for Array Destructuring
Davide Cannerozzi
Davide Cannerozzi

Posted on

Array Destructuring

Every Front end developer, sooner or later, will have to deal with arrays and objects.

Extrapolating data from an array may require several lines of code, but with the new es6 destructuring features, we can achieve the same goal with fewer lines of code.

In this article, I am going to teach you about Array Destructuring.

DESTRUCTURING IS A TOPIC YOU MUST KNOW IF YOU WANT TO BECOME A REACT DEVELOPER

To extract values from an array and push them into a variable, you would proceed like this.

const dogs = [‘Oliver’,’Winston’,’Carl’]

const first = dogs[0]
const second = dogs[1]
const third = dogs[2]

console.log( first, second, third ) 
Output: Oliver, Winston, Carl
Enter fullscreen mode Exit fullscreen mode

Everything works fine, but It can require many lines of code.

Now, Let’s see the process with the destructuring features.

const dogs = ['oliver', 'winnie', 'carl'];
const [first,second,third ] = dogs;

console.log(first,second,third)
Output: Oliver Winnie Carl
Enter fullscreen mode Exit fullscreen mode

Inside the square brackets, we declare the variables followed by an equal sign and the name of the array we want to destruct.

Each variable should match with the index of the element inside the array.

Array Destructuring

HOW TO SKIP ITEMS

What if you would like to output only the fourth array element?
You only have to use the comma, one comma skips one item in the array.

const numbers = [1,2,3,4]

const [, , ,num] = numbers

console.log(num)

Output : 4
Enter fullscreen mode Exit fullscreen mode

DESTRUCTURING AND THE SPREAD OPERATOR

If we want to get the rest of the elements from the initial array, we can use the … rest operator, another powerful ES6 feature.

const numbers = [1,2,3,4,5,6,7,8,9,10]

const [first,second,…rest] = numbers

console.log(first) Output: 1
console.log(second) Output: 2
console.log(rest)    Output: [3,4,5,6,7,8,9,10]
Enter fullscreen mode Exit fullscreen mode

DEFAULT VALUES

With Destructuring, we can use default values.
If a variable has no value or is undefined, we can use the equal sign to provide a fallback value.

const dogs = ['dave','carl',undefined,'winston']

const [first,second,third='oliver',fourth] = dogs

console.log(first)
console.log(second) 
console.log(third)  
console.log(fourth) 

Output: dave, carl,oliver,winston
Enter fullscreen mode Exit fullscreen mode
const numbers = [1,2,3]

const [a,b,c,d = 4] = numbers

console.log(a,b,c,d)

Output: 1 , 2 , 3 , 4
Enter fullscreen mode Exit fullscreen mode

You will use this feature often if your goal is to become a react developer.

Top comments (0)