Destructuring Assignment
Destructuring Assignment#
Extracting data from objects and arrays is among the most common operations in JavaScript. Destructuring gives us a concise syntax for extracting data and saving it to variables.
Destructuring Arrays#
In the example below, we define a yellow
array that represents an RGB color:
const yellow = [255, 255, 0];
Prior to ES2015, we would obtain the value of of an element in an array by index. To get the values of red, blue, and green that make up our yellow
above, we would do it like so:
const red = yellow[0]; // 255
const blue = yellow[1]; // 255
const green = yellow[2]; // 0
With destructuring, we no longer have to explicitly provide indeces. Instead, we specify the elements we want to extract based on their position in the array:
const [red, green, blue] = yellow;
console.log(red); // 255
console.log(blue); // 255
console.log(green); // 0
The order of the destructured variable names aligns with the order of the elements in the array. If we wanted to only extract the first element in the array, we can do so by ommitting the second and third values:
const [red] = yellow;
console.log(red); // 255
To only extract the third item in the array, we can use commas to indicate that we want to ignore the first two elements of the array:
const [,, green] = yellow;
console.log(green); // 0
Finally, if we want to save the first variable in an array to a variable and save the rest of the members of the array into a new array, we can do so by using the rest operator:
const [red, blueAndGreen] = yellow;
console.log(red); // 255
console.log(blueAndGreen); // [255, 0]
If we destructure an element that does not exist, the destructured variable will be undefined
at runtime:
This page is a preview of Beginners Guide to TypeScript