Execute Program

Modern JavaScript: Places Where Destructuring Is Allowed

Welcome to the Places Where Destructuring Is Allowed lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • We've already seen some examples of destructuring. In this lesson, we'll step back to see how these examples interact with one another and with other language features.

  • Destructuring works in function definitions. The destructuring rules are the same as when we destructure in a const or let statement.

  • >
    function getFirstArrayElement(array) {
    return array[0];
    }
    getFirstArrayElement(['cat', 'dog', 'horse']);
    Result:
    'cat'Pass Icon
  • >
    function getFirstArrayElement([first]) {
    return first;
    }
    getFirstArrayElement(['cat', 'dog', 'horse']);
    Result:
    'cat'Pass Icon
  • >
    function getUserName({name, age}) {
    return `${name}: ${age}`;
    }
    getUserName({name: 'Ebony', age: 26});
    Result:
    'Ebony: 26'Pass Icon
  • Here's a code problem:

    Finish this function that turns cat objects (like {name: 'Ms. Fluff', age: 4}) into cat summary strings (like 'Ms. Fluff (4)'). Use destructuring to extract name and age from the cat object.

    function catDescription({name, age}) {
    return `${name} (${age})`;
    }
    [
    catDescription({name: 'Ms. Fluff', age: 4}),
    catDescription({name: 'Keanu', age: 2}),
    ];
    Goal:
    ['Ms. Fluff (4)', 'Keanu (2)']
    Yours:
    ['Ms. Fluff (4)', 'Keanu (2)']Pass Icon
  • Destructuring also works in for-of loops.

  • >
    const users = [{name: 'Amir'}, {name: 'Betty'}];
    const names = [];
    for (const {name} of users) {
    names.push(name);
    }
    names;
    Result:
    ['Amir', 'Betty']Pass Icon
  • Destructuring can even be used in catch blocks!

  • >
    let userName = undefined;
    try {
    throw {name: 'Amir'};
    } catch ({name}) {
    userName = name;
    }
    userName;
    Result:
    'Amir'Pass Icon
  • There's a parallel here with "rest" parameters. Here are two ways to write a function named rest that returns an array with the first element removed. Both use destructuring to access the values.

  • The first way is to have the function take the array as an argument, but skip the first element with a , collecting the ...rest of the elements.

  • >
    function rest([, ...rest]) {
    return rest;
    }
    rest([1, 2, 3]);
    Result:
    [2, 3]Pass Icon
  • The second way is to have the function take multiple positional arguments. Here, note the _. That's a commonly-used name for an unused variable.

  • >
    function rest(_, ...rest) {
    return rest;
    }
    rest(1, 2, 3);
    Result:
    [2, 3]Pass Icon