Course outline · 0% complete

0/27 lessons0%

Course overview →

Destructuring

lesson 8-1 · ~11 min · 20/27

Quiz

Warm-up from lesson 7-2: `const g = evens(10);` has just run. How many numbers has the generator computed so far?

Unpacking values by shape

Destructuring pulls values out of objects and arrays by describing their shape on the left side of =.

  • Object: const { name, age } = user; grabs user.name and user.age by key.
  • Rename: const { name: userName } = user; reads key name into variable userName.
  • Default: const { role = "student" } = user; used only when the value is undefined.
  • Array: const [first, second] = list; unpacks by position instead of by key.

Destructuring exists because JavaScript functions receive bags of named data constantly — API responses, options objects, React props — and picking fields out with repeated user.something lines is pure noise. Nearly every modern file uses it, so reading it has to become automatic.

Code exercise · javascript

Run it. Four flavors in one program: plain keys, a rename, a default, and array positions.

Code exercise · javascript

Run it. Two bonus patterns worth knowing: array destructuring swaps two variables without a temporary, and object patterns nest to reach inner fields in one line.

In function parameters

The most common real-world spot is a function that takes an options object. Destructure right in the parameter list, defaults included:

function connect({ host, port = 80 }) {
  return host + ":" + port;
}

connect({ host: "api.dev" }); // "api.dev:80"

Callers pass named options in any order, and the function body gets clean local variables. You will see this pattern in nearly every JavaScript codebase and framework.

Quiz

`const { role = "student" } = { role: null };` What is `role`?

Code exercise · javascript

Your turn. Complete `describe` using PARAMETER destructuring: take `{ city, country = "unknown" }` and return `"<city>, <country>"`.