Array Destructuring
Destructuring assignment can be used for arrays as well, but with some reservations.
- Use square brackets
[]
instead of curly braces{}
. - All variables in square brackets
[]
will be successively assigned the values of the array elements.
For example, there is an array of colors from which you need to get the values of each color component and put them into separate variables.
const rgb = [200, 255, 100];
const [red, green, blue] = rgb;
console.log(`R:${red},G:${green},B:${blue}`); // "R:200,G:255,B:100"
After the keyword const
or let
, use the opening and closing square brackets, as when declaring an array. Inside the brackets, indicate the names of the variables (separated by commas), into which you will put the array values.
As a result, you will create 3 variables with elements placed in them in ascending order, from 0 to the array end.
When destructuring arrays, the value can be assigned to a variable after its declaration. In practice, this is rarely used.
const rgb = [200, 255, 100];
let red, green, blue;
[red, green, blue] = rgb;
console.log(`R:${red},G:${green},B:${blue}`); // "R:200,G:255,B:100"
If there are more variables than array elements, they will be assigned undefined
, so you can specify default values.
const rgb = [200, 100, 255];
const [red, green, blue, alfa = 0.3] = rgb;
console.log(`R:${red},G:${green},B:${blue},Alfa:${alfa}`); // "R:200,G:100,B:255,Alfa:0.3"
Sometimes only the first N
elements from an array need to be destructured, and the rest can be stored in a variable as an array. When destructing an array, you can unpack and assign the rest of the array elements to a variable using the ...
(rest) operation.
const rgb = [200, 255, 100];
const [red, ...colors] = rgb;
console.log(red); // "200"
console.log(colors); // [255, 100]
Some elements can be skipped. Suppose you only need to take the last value from the rgb
array. In practice, this feature is rarely used.
const rgb = [200, 100, 255];
const [, , blue] = rgb;
console.log(`Blue: ${blue}`); // "Blue: 255"