The destructuring syntax is a very handful feature to read arrays and objects, and extract data from them. It was a relatively recent addition to the language, but it’s generally available in all modern browsers.

If you have an object with many parameters, like this:

const breadIngredients = {
    warmWater: "2 cups",
    activeDryYeast: "1 tablespoon",
    salt: "2 teaspoons",
    vegetableOil: "2 tablespoons",
    breadFlour: "5 1/2 cups"
};

The destructuring assignment syntax lets you extract some properties from that object into variables. Let’s see an example

const { warmWater, vegetableOil } = breadIngredients;
console.log(warmWater); // Prints "2 cups"
console.log(vegetableOil); // Prints "2 tablespoons"

This created two new variables, warmWater, vegetableOil, in which we extracted the properties of the same name from breadIngredients.

This syntax is very useful when reading arguments in functions:

function listSomeBreadIngredients({ breadFlour, warmWater }) {
    console.log(`To make bread, you need ${breadFlour} of
        flour, ${warmWater} of warm water, and other ingredients.`);
}
listSomeBreadIngredients(breadIngredients);
// Prints "To make bread, you need 5 1/2 cups of
// flour, 2 cups of warm water, and other ingredients."

In this case, we passed the object breadIngredients to the function listSomeBreadIngredients. In the function, we extracted two properties (breadFlour and warmWater) from that object.

Another feature of object destructuring is the spread operator (...). It allows you to extract the rest of the properties. Let’s see an example:

const {warmWater, vegetableOil, ...otherIngredients} = breadIngredients;

Here, we extracted the properties warmWater and vegetableOil, and then we extracted all the other properties (i.e. activeDryYeast, salt, and breadFlour) into the variable otherIngredients:

console.log(otherIngredients);
/* Outputs:
{
  activeDryYeast: '1 tablespoon',
  salt: '2 teaspoons',
  breadFlour: '5 1/2 cups'
}
*/

You can do all of this with arrays too, you just have to use square brackets instead of curly ones:

const arrayBreadIngredients = [
    "warm water",
    "bread flour",
    "active dry yeast",
    "salt",
    "vegetable oil"
];

const [firstIngredient,
    secondIngredient,
    ...theRest] = arrayBreadIngredients;

console.log(firstIngredient);
// Outputs "warm water"

console.log(secondIngredient);
// Outputs "bread flour"

console.log(theRest);
/* Outputs:
[ 'active dry yeast', 'salt', 'vegetable oil' ]
*/

Join the newsletter!

Front end dev doesn't have to be hard! Tips and articles to help you become a better front-end dev.

    We won't send you spam. Unsubscribe at any time.