Destructuring
Learn how to extract one or more elements from an array or object, and rename object properties using destructuring.
Destructuring assignments
Destructuring allows us to extract one or more elements from any object or array and assign it to a new variable. It is another great syntax extension that has been gifted to us with the introduction of ES2015.
Destructuring arrays
Let’s imagine that we want to extract the medalists of a 100m run and write them to a new variable. ES5 allows us to express this in the following way:
const athletes = [
'Usain Bolt',
'Andre De Grasse ',
'Christophe Lemaitre ',
'Adam Gemili',
'Churandy Martina',
'LaShawn Merritt',
'Alonso Edward',
'Ramil Guliyev',
];
const gold = athletes[0];
const silver = athletes[1];
const bronze = athletes[2];
Thanks to destructuring, we can simplify this greatly and reduce the expression to a single statement:
const athletes = ['Usain Bolt','Andre De Grasse ','Christophe Lemaitre ','Adam Gemili','Churandy Martina','LaShawn Merritt','Alonso Edward','Ramil Guliyev',];const [gold, silver, bronze] = athletes;console.log(gold, silver, bronze);
The array elements at index 0
, 1
, and 2
are found in the variables for gold
, silver
, and bronze
. The result is the same as in the previous example, but the second version is shorter and more succinct.
We can use array destructuring anywhere the array has been initialized on the right side,
even if it is contained in the return
value of a function.
const getAllAthletes = () => {return ['Usain Bolt','Andre De Grasse ','Christophe Lemaitre ','Adam Gemili','Churandy Martina','LaShawn Merritt','Alonso Edward','Ramil Guliyev',]}const [gold, silver, bronze] = getAllAthletes()console.log(gold, silver, bronze);
As shown above, the array function returns an array with all the athletes. We can use destructuring directly once it is called, and we do not need to save the return
value in a temporary variable.
If we want to omit elements from the array, their values can be omitted like this:
const [, silver, bronze] = athletes;
In this example, we do not declare a variable gold
and we only save the silver
and bronze
medalists to our variables.
Array destructuring is not limited to assigning variables with let
and const
. There are many other cases that it can prove useful, such as when passing function arguments in the form of an array: