Destructuring Array In JavaScript: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about Destructuring Array In JavaScript.
Destructuring Array In JavaScript
In JavaScript, destructuring allows you to extract elements from arrays and assign them to variables. You can do this by using square brackets [] and the assignment operator (=) to assign the values of the array to the variables.
For example:
let myArray = [1, 2, 3];
let [a, b, c] = myArray;
console.log(a);
console.log(b);
console.log(c);
Output
1
2
3
In this example, the variables a
, b
, and c
are assigned the values of the first, second, and third elements of the myArray
array, respectively.
You can also use the spread operator (…) to assign the remaining values of an array to a variable.
let myArray = [1, 2, 3, 4, 5];
let [a, b, ...c] = myArray;
console.log(a);
console.log(b);
console.log(c);
Output
1
2
[3, 4, 5]
In this example, variable a
is assigned the value of the first element, variable b
is assigned the value of the second element, and variable c
is assigned the remaining values of the array as an array.