The basics of JavaScript destructuring

Published on

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.`);
// 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:

/* 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",
    "vegetable oil"

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

// Outputs "warm water"

// Outputs "bread flour"

/* Outputs:
[ 'active dry yeast', 'salt', 'vegetable oil' ]

Become a Better JavaScript Developer

Easy, actionable steps to level up your JavaScript skills, right to your inbox. Enter your name and Email address below to subscribe: