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:

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:

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:

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:

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:

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:

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

Please select a discussion on the left.