JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 9: Modern JavaScript SyntaxLesson 41 of 150About 40 minutes

Lesson 41: Destructuring

01Opening question

A function receives an order object but only needs its id and total. Is there a shorter way than writing order.id and order.total everywhere?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Destructuring copies values out of an object or array into variables in one statement.

const order = { id: 7, total: 42, status: "paid" };
const { id, total } = order;
console.log(id, total);
const [first, second] = ["red", "green", "blue"];
console.log(first, second);

03Objective and prerequisites

Learning objective: Unpack values from arrays and objects with destructuring, rename and default the unpacked variables, and destructure function parameters.

You need: Lesson 36: Creating JavaScript objects, Lesson 38: Nested objects and arrays

Skills practised: Destructuring.

04Explanation

Object destructuring creates variables named after properties: const { name, city } = user; is the same as writing const name = user.name; const city = user.city;.

Array destructuring unpacks by position: const [a, b] = [10, 20]; gives a = 10 and b = 20. Skip a position with an empty slot: const [, second] = list;.

Rename while unpacking with a colon: const { name: fullName } = user; creates fullName, not name.

Give a fallback with =: const { role = "viewer" } = user; uses "viewer" only when user.role is undefined.

05Definitions

Destructuring
Syntax that unpacks values from arrays or properties from objects into variables.
Object destructuring
Unpacking properties by name with const { a, b } = obj.
Array destructuring
Unpacking elements by position with const [a, b] = list.
Default value
A fallback used when the unpacked value is undefined.
Parameter destructuring
Destructuring an argument directly in a function's parameter list.

Open the full glossary

06Visual learning object

Destructuring visualizer. Pick a pattern and watch each variable receive its value, its default, or undefined.

Loading the interactive object…

Open the full Destructuring visualizer page with its guided experiment.

07Examples

ex-041-01Unpack an object Browser-executable JavaScript

Each name in the braces becomes a variable holding that property.

const user = { name: "Ada", city: "London", plan: "pro" };
const { name, plan } = user;
console.log(name);
console.log(plan);
Sample input
None
Expected output
Ada pro
Common mistake
Expecting the variable names to be free to choose; without a colon they must match the keys.
Try this
Also unpack city and print all three on one line.
Source
examples/ex-041-01-object-basics.js (repository pending publication)

ex-041-02Unpack an array Browser-executable JavaScript

Array destructuring works by position, and an empty slot skips one.

const podium = ["Grace", "Linus", "Ada", "Alan"];
const [gold, silver] = podium;
const [, , bronze] = podium;
console.log(gold, silver, bronze);
Sample input
None
Expected output
Grace Linus Ada
Common mistake
Using braces for arrays; braces match by name, so they would look for properties called gold and silver.
Try this
Unpack the fourth place too.
Source
examples/ex-041-02-array-basics.js (repository pending publication)

ex-041-03Rename and default Browser-executable JavaScript

A colon renames; = gives a fallback for undefined values.

const settings = { theme: "dark", fontSize: undefined };
const { theme: colorScheme, fontSize = 16, language = "en" } = settings;
console.log(colorScheme, fontSize, language);
Sample input
None
Expected output
dark 16 en
Common mistake
Reading theme after renaming it; only colorScheme exists.
Try this
Set fontSize to null and predict the output before running.
Source
examples/ex-041-03-rename-default.js (repository pending publication)

ex-041-04Destructured parameters Browser-executable JavaScript

Unpacking in the parameter list shows exactly which properties a function needs.

function label({ name, price, currency = "USD" }) {
  return `${name}: ${price} ${currency}`;
}
console.log(label({ name: "Lamp", price: 30 }));
console.log(label({ name: "Mug", price: 8, currency: "EUR" }));
Sample input
None
Expected output
Lamp: 30 USD Mug: 8 EUR
Common mistake
Calling label() with no argument, which throws because undefined cannot be destructured.
Try this
Give the parameter a default of {} and call label() with no argument.
Source
examples/ex-041-04-parameters.js (repository pending publication)

ex-041-05Swap two variables Browser-executable JavaScript

Destructuring an array literal swaps values without a temporary variable.

let left = "A";
let right = "B";
[left, right] = [right, left];
console.log(left, right);
Sample input
None
Expected output
B A
Common mistake
Leaving out the semicolon before a line that starts with [.
Try this
Rotate three variables a, b, c so a gets b, b gets c and c gets a.
Source
examples/ex-041-05-swap.js (repository pending publication)

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Fix the destructuring

Match destructured names to the object's keys.

const book = { title: "Dune", author: "Frank Herbert", pages: 412 };
const { name, writer } = book;
console.log(`${name} by ${writer}`);

Unpack coordinates

Use array destructuring with skipping and defaults.

const point = [12, 40];
// TODO: destructure x, y and z (z defaults to 0) from point
console.log(x, y, z);

Format an address

Destructure nested parameters with defaults.

// Write formatAddress({ street, city, country = "UK" } = {})

09Prediction

Commit to an answer first, then run the real code to compare.

const { a = 1, b = 2 } = { a: null, b: undefined };
console.log(a, b);

What is printed?

10Debugging investigation

The default theme never applies

Users without a saved theme should get "light", but the app shows "Theme: null".

const saved = { theme: null, fontSize: 14 };
const { theme = "light", fontSize } = saved;
console.log(`Theme: ${theme}`);

More cases in the Debugging Detective Laboratory

11Practical scenario

Reading API responses

A dashboard receives a large response object but each widget needs only a few fields. Destructuring at the top of each widget function names exactly what it reads and supplies safe defaults.

const response = { user: "ada", unread: 3 };
const { user, unread = 0, alerts = [] } = response;
console.log(`${user}: ${unread} unread, ${alerts.length} alerts`);

12Knowledge check

1. What is printed?

const { name, age } = { name: "Ada", age: 36 };
console.log(name, age);
  • Ada 36
  • undefined undefined
  • name age
  • An error

2. What is printed?

const [, , c] = [10, 20, 30];
console.log(c);
  • 10
  • 20
  • 30
  • undefined

3. In const { title: heading } = page;, which variable is created?

  • title
  • heading
  • both
  • page.heading

4. Why does this throw a TypeError?

function show({ size = 10 }) { return size; }
show();
  • show needs a return
  • show() passes undefined, which cannot be destructured
  • size is reserved
  • Defaults are not allowed in parameters

5. What is printed?

const { count = 5 } = { count: 0 };
console.log(count);
  • 0
  • 5
  • undefined
  • null

6. Which signature best documents the properties a function uses?

  • function save(options)
  • function save({ id, name, overwrite = false })
  • function save(a, b, c, d)
  • function save(...args)

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Fix the destructuring: Prints title and author; Uses renaming
  • Unpack coordinates: Prints 12 40 0; z is 0
  • Format an address: Prints both addresses; Country can be given; No argument does not throw
  • ex-041-01: output matches the documented expected output
  • ex-041-02: output matches the documented expected output
  • ex-041-03: output matches the documented expected output
  • ex-041-04: output matches the documented expected output
  • ex-041-05: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-09-modern-javascript-syntax/lesson-041-destructuring/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • Object destructuring unpacks by name; array destructuring by position.
  • A colon renames; = supplies a default for undefined.
  • Destructure parameters to document what a function needs.
  • Give destructured parameters a default of {} when the argument is optional.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation destructuring
Context: I am learning destructuring in JavaScript.
Task: Explain object and array destructuring, renaming and defaults with a user settings example.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction destructuring drill
Context: I have practised destructuring.
Task: Give me six destructuring snippets, including defaults with null and undefined, and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging destructuring bug
Context: My destructured variable is undefined even though the object has the data.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation destructuring practice
Context: I finished the destructuring exercises.
Task: Create three exercises that use destructuring on API-style responses.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review destructuring review
Context: Here is my code that uses destructuring.
Task: Review my functions and suggest where destructured parameters would make them clearer.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.