
Array Destructuring
20 January, 2023
6
6
0
Contributors
What is Array Destructuring in JavaScript?
JavaScript array destructuring is a feature that allows you to extract values from an array and assign them to variables using a concise syntax. It is a way to extract data from arrays, or properties from objects, into distinct variables. The basic syntax of array destructuring is as follows:
let myArray = [1, 2, 3, 4, 5];
let [a, b, c] = myArray;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
In this example, the array's
first, second and third elements are assigned to variables a
, b
, and c,
respectively.
You can destructure specific elements using their index as well:
let myArray = [1, 2, 3, 4, 5];
let [, second, , fourth] = myArray;
console.log(second); // 2
console.log(fourth); // 4
Destructuring in Function Argument
You can also use destructuring in function arguments
function printElements([first, second, third]) {
console.log(first);
console.log(second);
console.log(third);
}
printElements([1, 2, 3]);
Note we pass an array as a parameter to the printElements()
function while invoking it. In the function definition, we destructure the array elements in its argument itself.
Default Value in Destructuring
It's worth noting that you can use the default value in case the variable is not defined in the array.
let myArray = [1];
let [a, b=2] = myArray;
console.log(a); // 1
console.log(b); // 2
In the example above, the array has only one element. While destructuring, we can create another variable and assign it to a default value. In this case, the new variable value was never part of the array.
Array destructuring can be a powerful tool for working with arrays. It helps you write more readable and concise code by eliminating the need to access elements of an array using their indices.