Array Destructuring in Javascript


Javascript array destructuring, introduced in ES6 Javascript, is a programming technque that makes it possible to extract values from data such as arrays, objects, and strings, into variables. It provides a very concise way to extract multiple values from an array into variables and avoids repetitive array indexing.

Given an array data, we can extract the values of specific array elements and ignore those that we do not need. In addition, we can use array destructuring to easily swap the values of two variables without the need to declare a temporal variable.

In this post, we will demystify Javascript array destructuring and understand how it simplifies array operations such as array concatenation, array cloning, extraction of values from nested arrays, etc.

Destructuring Assignment

In javascript, destructuring assignment is an expression that makes it possible to selectively extract all or part of an array or object data and store them in specific variables in a single statement. In other words, destructuring assignment is an expression that allows for the unpacking of array and object data into variables.

Destructuring assignment was introduced in ES6 (ECMAScript 2015) Javascript. Before its introduction, we normally access the elements of an array by typing the name of the array followed by the index of the element enclosed in square brackets.

For example, let’s suppose we have an array of programming languages, as shown below:

JavaScript
let languages = ['Javascript', 'PHP', 'Python', 'Java'];

In the pre-ES6 era, if we need to extract the array elements into variables, we will need to use array indexing to get the specific elements and store them in variables:

JavaScript
let languages = ['Javascript', 'PHP', 'Python', 'Java'];

// extract array elements into defined variables
let var1 = languages[0];  // will contain Javascript
let var2 = languages[1];  // will contain PHP
let var3 = languages[2];  // will contain Python
let var4 = languages[2];  // will contain Java

// log values
console.log(var1, var2, var3, var4);  // output: Javascript PHP Python Java

In our attempts to extract the array elements into variables, we used array indexing to extract the array items from the array and saved them in variables: var1, var2, var3, and var4. This technique is very common and works very well. However, ES6 Javascript has a better way of handling such assignments.

The ES6 Javascript introduces a very compact way of assigning array elements to variables without repetitive array indexing. With this approach, we can extract array elements and assign them to variables, all in just a single expression or statement. Consider the following code listing:

JavaScript
let languages = ['Javascript', 'PHP', 'Python', 'Java'];

// extract array elements into defined variables
let [var1, var2, var3, var4] = languages;

// log values
console.log(var1, var2, var3, var4);  // output: Javascript PHP Python Java

The expression [var1, var2, var3, var4] = languages on line 4 is called destructuring assignment. The expression declares multiple variables and maps them to the elements in the languages array in the same order.

Think of the destructuring assignment as simultaneously declaring multiple variables, var1, var2, var3, and var4, and then unpacking the elements of the languages array into these variables. During unpacking, the values of the languages array elements are extracted into the declaration variables in the same array indexing order.

For example, since var1 has index 0, it will correspond with languages[0], and therefore its value will be Javascript. Since var2 has index 1, it will correspond with languages[1] and therefore its value will be PHP, and var3, with index 2, will have the value Python, and so on..

Now compare listing 3 to listing 2. If you are not already familiar with destructuring assignment in Javascript, then I bet you are beginning to love this programming construct, considering its compactness and the cleaner code it offers.

But that is not all. There are a lot that can be done with array destructuring, and we will cover them in this post. For example, destructuring assignment enables us to selectively extract specific elements of an array into variables and ignore those we do not need.

Destructuring Assignment Syntax

Before we dive deeper into array destructuring, it is important to understand the basic syntax for destructuring assignment. We will consider this basic syntax for both arrays and objects. The discussion on object destructuring is extensiviely discussed in a separate post, and can be accessed at Javascript Object Destructuring.

When extracting data from an array, the destructuring declaration variables need to be enclosed in square brackets: []. For example:

JavaScript
// In array destructuring, declaration
// variables are enclosed in brackets: []
let [var1, var2, var3] = ArrayData;

The names enclosed in brackets are variables into which we want to store the extracted values from the array. Therefore, these names must conform to Javacript variable naming considerations.

If we need to destructure values from an object, we use braces (square brackets), {}, to enclose the declaration variables into which we store the extracted values:

JavaScript
// In object destructuring, declaration
// variables are enclosed in braces: {}
let {var1, var2, var3} = ObjectData;

From the discussions so far, we can identify that the general syntax for destructuring arrays and objects are very similar, as shown below:

JavaScript
let [] = ArrayData;
let {} = ObjectData;

Thus, when destructuring an array, we use brackets, [] to enclose the variables in the destructuring declaration expression. For object destructuring, we use braces, {}, to enclose the declaration variables.

In the discussions that follow, we will delve deeper into array destructuring. We consider javascript object destructuring in a separate post.

Array Destructuring

The ES6 Specification introduces array destructuring assignment through which we can assign the elements of an array to multiple variables in just a single statement. This eleminates the need to index the array elements one at a time in order to get the element values we need, as done in listing 2.

For example, given that we have an array of countries as shown below:

JavaScript
// array declaration
const countries = ['Ghana', 'Canada', 'United States', 'Germany'];

const var1 = countries[0];
const var2 = countries[1];
const var3 = countries[2];
const var4 = countries[3];

Using array destructuring statement, we can rewrite listing 7 as the following:

JavaScript
// array declaration
const countries = ['Ghana', 'Canada', 'United States', 'Germany'];

// extract individual array elements into variables
const [var1, var2, var3, var4] = countries;

Line 5 is an array destructuring statement. This statement declares the variables var1, var2, var3, and var4, and then initializes them to the elements of the initializer array, countries. The elements in the initializer array are assigned to the variables by mapping each variable in the destructuring declaration to an element in the initializer array in the same order.

To understand this better, think of the destructuring declaration [var1, var2, var3, var4] as an array. Then variable var1 has index 0 and so maps to countries[0], var2 has index 1 and so maps to countries[1], var3 has index 2 and so maps to countries[2], and so on; These mappings and extraction of values are done by Javascript so that we do not need to assign the elements in the countries array one at a time with array indexing. With destructuring assignment, we are able to do all at once.

Separating Variable Declarations from Assignment

In destructuring assignment, we are not mandated to always declare new variables for the assignment. Existing variables can be used in the destructuring declaration to assign values from the initializer array. An example is shown in the following code listing:

JavaScript
// array declaration
const countries = ['Ghana', 'Canada', 'United States', 'Germany'];

// declare target variables
let var1, var2, var3, var4;

// extract individual array elements into variables
[var1, var2, var3, var4] = countries;

// log the values
console.log(var1);  // var1: Ghana
console.log(var2);  // var2: Canada
console.log(var3);  // var3: United States
console.log(var4);  // var4: Germany

The variables var1, var2, var3, and var4 are declared separately on line 5. Then on line 8, we use array destructuring statement to assign the initializer array elements to the already declared variables.

As can be seen, we group the variables that we want to assign values in brackets, and then assign them to the initializer array. Javascript will automatically map the variables to the initializer array in order, and extract the values from the initializer array elements into the variables.

Variables Unmapped to Initializer Array Elements Are undefined

We have indicated that in an array destructuring statement, Javascript maps each item in the destructuring declaration array to items in the initializer array. However, if an item in the declaration array does not map to an item in the initializer array, then the value of that variable is undefined. This happens when the number of variables in the destructuring declaration array is more than the number of items in the initializer array.

Consider the following code listing:

JavaScript
// array declaration
const languages = ['PHP', 'Java', 'Javascript'];

// destructure the array into variables
const [var1, var2, var3, var4] = languages;

// log value of var4
console.log(var4);  // output: undefined

Observe that there are four destructuring declaration variables: var1, var2, var3, and var4. However, The initializer array, languages, has only three items.

In destructuring the initializer array, var1 maps to languages[0], var2 maps to languages[1], and var3 maps to languages[2]. However, var4 does not map to any element in the languages array. The result is that var4 is declared as a variable without an initializing value, similar to a variable declaration like the following which will have undefined as its value:

JavaScript
// declaration of variable without initializing value
const var4;

Thus, the value of a variable in the declaration array which is not mapped to an element in the initializer array will be undefined.

Setting Default Values for Variables

When destructuring an array into variables, we can set default values to be used when the value of a variable is undefined.

For example, in the previous section, we indicated that if a variable in the destructuring declaration array is not mapped to an element in the initializer array, then its value will be undefined.

If we like, we can provide a default value which should be used if the value of a variable is undefined after the array destructuring. To do this, we assign the default value to the variable in the declaration array:

JavaScript
// array declaration
const languages = ['PHP', 'Java', 'Javascript'];

// destructure the array into variables
const [var1, var2, var3, var4 = 'Python'] = languages;

// log value of var4
console.log(var4);  // output: Python

In the destructuring of the array on line 5, var4 does not map to any item in the languages array and therefore should have its value to be undefined. However, on this same line, we assign a default value to var4. The default value will be used if the value of var4 is undefined after destructuring.

Default values can be assigned to multiple variables in the destructuring declaration array. However, these default values are only used if the value extracted from the initializer array is undefined or when the variable has no mapping in the initializer array. For example:

JavaScript
// array declaration
const languages = ['PHP', 'Java', 'Javascript'];

// destructuring declaration array
const [var1 = 'C#', var2 = 'C++', var3 = 'C', var4 = 'Python'] = languages;

// log values
console.log(var1);  // output: PHP
console.log(var2);  // output: Java
console.log(var3);  // output: Javascript
console.log(var4);  // output: Python

On line 5, we have set default values for all the variables in the destructuring declaration array. When mapped to the initializer array, we can observe that the values that will be extracted from the languages array for var1, var2, and var3 are not undefined. Therefore, the corresponding values in the initializer array are used rather than the default values. var4 which is not mapped to an element in the initializer array, and expected to be undefined, will use the default value set in the declaration array.

Let’s deliberately change the vaue of the first element in languages array to undefined:

JavaScript
// array declaration
const languages = [undefined, 'Java', 'Javascript'];

// destructuing declaration array
const [var1 = 'C#', var2 = 'C++', var3 = 'C', var4 = 'Python'] = languages;

// log value of rust variable
console.log(var1);  // output: C#
console.log(var2);  // output: Java
console.log(var3);  // output: Javascript
console.log(var4);  // output: Python

After re-running the code, we should expect the value of var1 to be the default value set in the destructuring declaration array. This is because var1, which maps to languages[0], will have its value being undefined, and therefore the default value instead gets assigned to var1.

Skipping to Selectively Extract Values

Sometimes, we may not need all the data that is contained in a given array. We may need the value of only one or a few of the array elements. If the array elements that we need aren’t contiguous, especially not at the beginning, then that will imply that we skip those that we do not need and extract those that we need.

Consider an initial array data below:

JavaScript
// array declaration
const countries = ['Ghana', 'Canada', 'United States', 'Germany'];

Let’s suppose we are only interested in getting the values of the second, third and fourth array elements. In the pre-ES6 era, we will use array indexing to access the values, such as in the following code listing:

JavaScript
// array declaration
const countries = ['Ghana', 'Canada', 'United States', 'Germany'];

const var1 = countries[1];
const var2 = countries[2];
const var3 = countries[3];

With ES6 array destructuring, we can skip values by omitting variables names in the declaration array. To skip the first array item in the initializer array, we will omit the variable name from the declaration array. The comma is however important. It is an indication that we intend to ignore extraction of the value at that index.

JavaScript
// array declaration
const countries = ['Ghana', 'Canada', 'United States', 'Germany'];

// ignore first item, and extract the rest
const [, var2, var3, var4] = countries;

Take a careful look at line 5. In the destructuring declaration array, there is no variable name specified before the first comma. We can identify that the position of the first item in the declaration array is blank, signalling that we intend to skip the mapping of the first array element in the initializer array.

Let’s again suppose we intend to extract only the second and fourth elements from countries array. Since we want to ignore the first array element (index 0), and the third array element (index 2), we will not provide any variable names at the indexes we intend to ignore in the declaration array:

JavaScript
// array declaration
const countries = ['Ghana', 'Canada', 'United States', 'Germany'];

// ignore first and third items, and extract second and fourth
const [, var2, , var4] = countries;

// log values
console.log(var2);  // output: Canada
console.log(var4);  // output: Germany

Now what if we intend to extract only the last element from countries? Again, we will not provide variable names at the indexes we intend to ignore:

JavaScript
// array declaration
const countries = ['Ghana', 'Canada', 'United States', 'Germany'];

// ignore first three items, and extract the last
const [, , , var4] = countries;

// log values
console.log(var4);  // output: Germany

On line 5, the first comma skips the first element in countries, the second comma skips the second element in countries, and the third comma skips the third element in countries. var4, then, maps to countries[3].

Swapping Values of Two Variables

Javascript array destructuring construct enables us to easily swap the values of two variables without the need to explicitly declare a third variable.

Before array destructuring was introduced in ES6 Javascript, you will declare a third variable as a temporary storage space in order to swap the values of two variables. The following code listing is a reminder of how it used to be done:

JavaScript
// variables declaration
let var1 = 50;
let var2 = 80;

// we need a temporal variable to store one of them
const temp = var1;

// swap values of var1 and var2
var1 = var2;
var2 = temp;

// log variables
console.log(`var1=${var1}`);    // output: var1=80
console.log(`var2=${var2}`);    // output: var2=50

With array destructuring, we can swap the values of two variables in just a single statement. This is done by changing the order of the variables in the declaration array and the initializer array. The following code listing is an example:

JavaScript
// variables declaration
let var1 = 50;
let var2 = 80;

// swap values of var1 and var2, 
[var1, var2] = [var2, var1];

// log variables
console.log(`var1=${var1}`);    // output: var1=80
console.log(`var2=${var2}`);    // output: var2=50

Observe line 9 carefully. We use the two variables that we want to swap their values in the declaration array and the initializer array. You should notice that the order of the declaration array items and the initializer array items are in opposite order.

In the declaration array, var1 is declared as the first item followed by var2. Then in the initializer array, var2 appears before var1. This means that we have interchanged the order of var1 and var2 in the declaration array and the initializer array. In fact, this is the only single statement we need in order to swap their values, nothing more. After running the code, you should see that the values of these two variables have been swapped.

Using Rest Syntax to Assign Remaining Values

Sometimes, we may need to extract specific elements into separate variables and then extract the remaining elements into some other variable. We can achieve this by using the rest operator introduced in ES6 javascript.

The rest operator is a three consecutive dots, (...), operator, which precedes a variable in a destructuring declaration. It used to pack the rest, or remaining values of an iterable, such as an array, into the variable preceded with the rest operator.

Consider the following code listing:

JavaScript
// array declaration
const countries = ['Ghana', 'Spain', 'France', 'Germany'];

// extract first item into africa, then pack the remaining into europe
const [africa, ...europe] = countries;

// log values
console.log(africa);    // output: Ghana
console.log(europe);   // output: ['Spain', 'France', 'Germany']

On line 5, the variable africa maps to countries[0]. The rest operator, ..., preceding the variable europe, that is, ...europe, means that the rest of the elements, starting from the index mapping of where the rest operator is used, should all be packed into the variable preceded with the rest (...) operator.

Thus, after destructuring, europe will be an array containing the rest of the elements of the countries, starting from the indexing mapping of europe (countries[1]) to the initializer array, countries.

Considering another example, we can decide to extract the first two items and pack the rest in a different variable:

JavaScript
// array declaration
const countries = ['Ghana', 'Spain', 'France', 'Germany'];

// extract first and second, then pack the rest in different variable
const [ghana, spain, ...rest] = countries;

// log values
console.log(ghana);  // output: Ghana
console.log(spain);  // output: Spain
console.log(rest);   // output: ['France', 'Germany']

Using Spread Syntax to Expand Array Elements

The Javascript spread syntax is an expression that expands an iterable data, such as array, string, or object, into individual elements separated by commas. Like the rest syntax, the spread syntax also uses three consecutive dots, (...), preceding an iterable variable to expand the iterable data into individual elements separated with commas.

For example, to spread the elements of an array, we precede the array variable name with the spread operator, (...). An example is shown in the following code listing:

JavaScript
// array definition
const data = [1, 2, 3, 4, 5];

// spread the array items
console.log(...data);

On line 5, we precede the array variable name, data, with three consecutive dots (...). This expands the array into individual items separated by commas. The effect is that line 5 expands to the following call:

JavaScript
// ...data expands the array elements, separated by commas
console.log(1, 2, 3, 4, 5);

It is important to understand that passing an array as argument to a function call and spreading an array as argument to a function call are not the same. Hence, in the following code listing, the calls to the log method of the console object are not the same:

JavaScript
// array definition
const data = [1, 2, 3, 4, 5];

console.log(data);      // output: [1, 2, 3, 4, 5]
console.log(...data);   // output: 1 2 3 4 5

On line 4, we pass the array as argument to the log method without preceding it with the spread operator. In this case, we are passing only one argument to the log method. This, logs data as array in the console.

On line 5, we precede the array with the spread operator. This expands the array by spreading and separating the individual array elements with commas. Thus, after spreading the array, we are actually passing five arguments to the log method.

With the basic understanding gained so far, we should look at other code logic in which the spread syntax can be used.

Cloning An Array Using Spread Syntax

When we assign an array to another variable, the two variables become arrays pointing to the same array data. For example:

JavaScript
// initialise array
let A = [1, 2, 3, 4];

// assign A to new variable B
let B = A;

// log values
console.log('A = ', A);
console.log('B = ', B);

As expected, both A and B will have the same values.

However, if we modify an element in A, it will affect the values in B:

JavaScript
// initialise array
let A = [1, 2, 3, 4];

// assign A to new variable B
let B = A;

// modify fourth element in A
A[3] = 10;

// log values
console.log('A = ', A);
console.log('B = ', B);

On line 8, we modify the value of the fourth element in A. However, this also updates the value of the fourth element in B, as shown below:

This happens because A and B have the same reference to the array data.

We can use the ES6 Javascript spread syntax to easily clone the values of one array into another so that they will not reference the same array data. Rather than assign A to B, as we did on line 5 in listing 29, we will spread the elements of A to initialize a new array which will be assigned to B:

JavaScript
// initialise array
let A = [1, 2, 3, 4];

// assign A to new variable B
let B = [...A];

// modify an element in A
A[3] = 10;

// log values
console.log('A = ', A);
console.log('B = ', B);

On line 5, we set B to a new array that we initialize by spreading the elements A within brackets, []. This makes A and B have different references to array data, although they have the same values. An update to array A on line 8 does not affect array B, as shown in the following log output:

Thus, array A is a clone of array B. It should however be noted that this approach only creates a shallow copy of the source array.

Concatenating Arrays

The spread syntax can also be used to concatenate two arrays. Before ES6, it was common to use the concat method of an array to concatenate two arrays. With ES6, we can use the spread syntax to achieve same.

Suppose we have two arrays, given in the following code listing:

JavaScript
// array declarations
const A = [1, 2, 3, 4];
const B = [5, 6, 7, 8];

// concatenate A and B
const C = [...A, ...B];

console.log(C);  // output: [1, 2, 3, 4, 5, 6, 7, 8]

On line 6, we use the spread syntax to expand arrays A and B. The effect is that a new array is initialized with its content being the values of both arrays A and B, and assign the generated array to C.

Destructuring Array in Function Arguments

If a function accepts arguments in its call, and we have the values to be passed to the function in an array, there is no need to use array indexing to set the argument values. If the ordering of the array elements correctly map to the function parameters, we can use the spread syntax to spread the argument values.

For example, suppose we have the following function which has three parameters:

JavaScript
// function definition
function getVolume(width, length, height) {
     return width * length * height;
}

Suppose also that we have the values to be passed to the function in an array with correct mapping of the array elements to the parameters:

JavaScript
// object shape data [width, length, height]
const data = [3, 5, 4];

Without array destructuring, we will pass the values to the function by indexing the array:

JavaScript
// object shape data [width, length, height]
const data = [3, 5, 4];

// calculate object volume
let volume = gettVolume(data[0], data[1], data[2]);

With array destructuring, we can spread the array elements when calling the function:

JavaScript
// object shape data [width, length, height]
const data = [3, 5, 4];

// calculate object volume
let volume = getVolume(...data);

As can be seen, using the spread syntax involves less typing when compared to accessing the values with array indexing.

Destructuring Array in Function Parameters

Traditionally, when an array is passed as argument to a function, we access the values of the array in the function by using array indexing to retrieve the individual array elements. For example, suppose we have a function that calculates the volume of an object based on values passed to it as array:

JavaScript
function getVolume(arrData) {
    const width = arrData[0];
    const length = arrData[1];
    const height = arrData[2];
    
    // calculate and return volume
    return width * length * height;
}

Rather than use array indexing to retrieve the values into variables, we can use ES6 array destructuring construct to destructure the array parameter into individual variables without the need to access the values with array indexing. But before we see how this is done, let’s understand what happens when we pass a value as argument to a function.

Suppose we have a function that accepts a value in its call, such as the following:

JavaScript
function someFunction(PARAM) {
    return PARAM * 2;
}

As we know, we will call the function by passing a value to it as an argument:

JavaScript
// call the function
someFunction(ARG);

When the function is called, the value of ARG is assigned to the variable PARAM declared in the function’s signature. This implies that the function call leads to assignment of ARG TO PARAM:

JavaScript
PARAM = ARG

Now suppose ARG is an array, [1, 2, 3], and we pass it as argument to the function, this results in the assignment of the array to PARAM declared in the function signature:

JavaScript
PARAM = [1, 2, 3];

But in our early discussions on array destructuring, we indicated that we can destructure an array into different variables, such as the following:

JavaScript
[width, length, height] = [1, 2, 3];

With this understanding, we can rewrite arrData in getVolume() function by replacing it with destructuring declaration variables:

JavaScript
function getVolume([width, length, height]) {
    // calculate and return volume
    return width * length * height;
}

Thus, if a function accepts an array as an argument, then we can destructure the array parameter into declaration variables directly in the function header without the need for array indexing to retrieve the individual values into separately declared variables.

Destructuring Nested Arrays

We can apply our understanding of array destructuring so far to destructure an array within an array. As we will soon see, that is a very easy task, though it may seem daunting at first encounter. We will take step by step approach to better your understanding of nested array destructuring.

First, let’s assume we have the following nested array:

JavaScript
const numbers = [0, [1, 2, 3]];

We can identify that the array numbers has two elements. The first element, numbers[0], has the value 0, and the second element, numbers[1] has an array, which is [1, 2, 3].

Our task is to extract all the numerical values into variables. We will name the variables after the number we want to retrieve, such as one, two, three, etc. Let’s see how we can do this with array destructuring.

First, let’s observe again that the numbers array has two elements. Suppose we destructure the array into two variables, A and B:

JavaScript
const numbers = [0, [1, 2, 3]];

// destructure into variables
const [A, B] = numbers;

In this code listing, A maps to numbers[0] which has the value 0, and B maps to numbers[1] which is an array: [1, 2, 3]. Since B is an array, we can further destructure it into additional declaration variables. But since we already know that A has the value 0, lets replace it with variable name zero which is its numerical value that we extract, and then continue from there:

JavaScript
const numbers = [0, [1, 2, 3]];

// destructure into variables
const [zero, B] = numbers;

Recall that B maps to numbers[1], which is an array: [1, 2, 3]:

JavaScript
B = [1, 2, 3];

We can now destructure B into additional declaration variables with the names of the values in the array:

JavaScript
const [one, two, three] = B

We can replace B with the declaration variables: [one, two, three]. Hence, on line 4 in listing 45, we can substitute [one, two, three] in place of B:

JavaScript
const numbers = [0, [1, 2, 3]];

// destructure into variables
const [zero, [one, two, three]] = numbers;

// log the values
console.log(zero, one, two three);  // output: 0 1 2 3

Using array destructuring syntax, we have been able to destructure both the outer array and the inner array of numbers into distinct variables.

Let’s further test our understanding of nested array destructuring with another challenge by updating the numbers array to the following:

JavaScript
const numbers = [0, [1, 2, [3, 4]]];

We can identify that the numbers array has two elements. The first item, numbers[0], has the value 0. The second item, numbers[1], has its value to be an array, which is [1, 2, [3, 4]]. Further, we can identify that numbers[1][2] also contains an array which is [3, 4].

Going by the approach discussed earlier, we can destructure the values in the numbers array into variables as shown in the following code listing:

JavaScript
const numbers = [0, [1, 2, [3, 4]]];

// destructure into variables
const [zero, [one, two, [three, four]]] = numbers;

// log the values
console.log(zero, one, two, three, four);  // output: 0 1 2 3 4

Javascript array destructuring syntax is not only elegant but also a time-saving approach. In just a single statement, we have been able to extract values of array elements, event nested ones, into distinct variables.

Wrapping Up

Javascript array destructuring is a programme technique introduced in ES6 Javascript which makes it possible to unpack an array and store the individual elements into variables. This can be done in just a single statement without the need to index the array to extract the values.

For example, given the following array:

JavaScript
// array declaration
const numbers = [1, 2, 3, 4];

We can use array destructuring assignment syntax to extract all the values from the array in just a single statement:

JavaScript
// array declaration
const numbers = [1, 2, 3, 4];

// extract values
const [one, two, three, four] = numbers;

The declaration assignment syntax on line 5 declares variables one, two, three, and four, and then maps each variable to the numbers array in order. In this case, one maps to numbers[0], two maps to numbers[1], three maps to numbers[2], and four maps to numbers[3].

If we do not need all the values from the initializer array, then we can skip specific values in the initializer array by ommiting variable names that should map to the elements we want to skip. For example, if we want to skip the first element in numbers, then we will not provide any variable name in the declaration array:

JavaScript
// array declaration
const numbers = [1, 2, 3, 4];

// ignore first element
const [, two, three, four] = numbers;

Observe that there is variable name before the first comma, indicating that we want to skip this mapping into the numbers array.

If we want to skip the first and second elements, then following will do:

JavaScript
// array declaration
const numbers = [1, 2, 3, 4];

// ignore first and second elements
const [, , three, four] = numbers;

Sometimes, we may choose to extract specific value and pack the remaining ones into another variable. We can pack the remaining elements into a variable using the rest operator, (...). For example:

JavaScript
// array declaration
const numbers = [1, 2, 3, 4];

// extract first element, and pack the remaining into different variable
const [one, ...others] = numbers;

console.log(one);   // output: 1
console.log(rest);  // output: [2, 3, 4]

In this code listing, one maps to numbers[0]. The rest operator in frot of others implies that starting from the current mapping, the remaining ones should all be packed into others variable.

We can even use array destructuring syntax to swap values of two variables. For example:

JavaScript
let first = 10, second = 20;

// swap their values
[first, second] = [second, first];

// log the values
console.log(first);  // output: 20
console.log(second); // output: 10

We can extend array destructuring syntax to destructure array parameters in functions:

JavaScript
function getTotal([var1, var2, var3]) {
    return var1 + var2 + var3;
}

const data = [10, 20, 30];

// get total
let total = getTotal(data);

Other operations that can performed with Javascript array destructuring include concatenation and shallow cloning of arrays. It can also be used to simplify extraction of values from nested arrays.


Leave a Reply

Your email address will not be published. Required fields are marked *