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
constorletstatement.>
function getFirstArrayElement(array) {return array[0];}getFirstArrayElement(['cat', 'dog', 'horse']);Result:
'cat'
>
function getFirstArrayElement([first]) {return first;}getFirstArrayElement(['cat', 'dog', 'horse']);Result:
'cat'
>
function getUserName({name, age}) {return `${name}: ${age}`;}getUserName({name: 'Ebony', age: 26});Result:
'Ebony: 26'
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 extractnameandagefrom thecatobject.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)']
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']
Destructuring can even be used in
catchblocks!>
let userName = undefined;try {throw {name: 'Amir'};} catch ({name}) {userName = name;}userName;Result:
'Amir'
There's a parallel here with "rest" parameters. Here are two ways to write a function named
restthat 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...restof the elements.>
function rest([, ...rest]) {return rest;}rest([1, 2, 3]);Result:
[2, 3]
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]