Destructuring Arrays in JavaScript

Simeon Kengere
Webtips
Published in
3 min readJun 23, 2022

Destructuring was first introduced in JavaScript version ES6 2015 to help extract data from iterables (arrays, objects, maps) into separate variables.

For arrays, destructuring is used to retrieve elements from an array and store them into variables in a simplified form. Consider the following array:

Declaring array arr

Without destructuring, we would retrieve the elements from array arr as follows:

Retrieving elements from array arr

With destructuring, we can declare all the 4 variables at the same time using square brackets as follows:

Retrieving elements from array arr with destructuring

When we log the results to the console, the following will be the output:

Notice when we destructure, [i,j,k,l] looks like we are declaring an array, but we are not. This is simply the destructuring assignment. So whenever JavaScript sees [i,j,k,l] on the left side of the assignment operator (=), it knows that it should do destructuring. It is also important to remember to declare the variables using const.

Even though we did destructuring, it is important to note that the original array is not affected. We can see this in the snippet below:

Let us look at another example. Consider the following array:

Let us assume we want to get the first 2 elements out of the array. We could achieve this in the following way:

In addition, let us assume we would want to take the first and the third elements only out of the array (football and tennis). To do that, we simply leave a hole in the destructuring operator as follows:

In the destructuring assignment above, the second element in the array (arr[1]) will be skipped, then the ‘second’ variable declared in the destructuring assignment will now become the third element in the array (arr[2]).

In conclusion, it is important to note that browsers that do not support JavaScript version ES6 2015 may not support the use of the destructuring syntax. Visit JavaScript destructuring support to learn more.

--

--

Simeon Kengere
Webtips
Writer for

Software Engineer || Software developer. Come hang out with me on twitter: https://twitter.com/KengereSimeon