Destructuring Assignment
Reviewed & published by Brayan K
Destructuring is the modern way to unpack values out of arrays and objects into their own variables — in a single, readable line. If you've ever written const name = user.name; const age = user.age; three times in a row, this lesson is about to save you a lot of typing.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
It's everywhere in real codebases: React props, API responses, function options, and module imports all lean on it heavily.
What You'll Learn in This Lesson
- Unpack arrays by position
- Unpack objects by name
- Rename properties on the fly
- Set default values for missing data
- Destructure nested objects safely
- Destructure function parameters
📚 Prerequisites: You should know how variables, arrays, and objects work. Destructuring is just a shortcut for reading values you already understand.
💡 Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:
- Download Node.js to run JavaScript on your computer
- Use your browser's Developer Console (Press F12) to test code snippets
- Create a .html file with <script> tags and open it in your browser
📦 Real-World Analogy: Destructuring is like unpacking a delivery box:
- • The box (array/object) arrives full of items
- • Instead of reaching back in every time, you lay each item on the counter with its own label
- • Arrays are unpacked by position (first item, second item…)
- • Objects are unpacked by name (the item labelled "title", the one labelled "price")
1️⃣ Array Destructuring — Unpack by Position
Wrap variable names in square brackets on the left of =. They fill up from the array in order. You can skip elements with a bare comma, and grab "the rest" with the ...rest syntax.
const rgb = [255, 160, 0];
// Old way:
// const r = rgb[0]; const g = rgb[1]; const b = rgb[2];
// Destructured:
const [r, g, b] = rgb;
console.log(r, g, b); // ✅ Expected output: 255 160 0
// Skip elements with a bare comma
const [first, , third] = ["gold", "silver", "bronze"];
console.log(first, third); // ✅ Expected output: gold bronze
// Grab the rest into an array
const [winner, ...others] = ["Ada", "Linus", "Grace"];
console.log(winner); // ✅ Expected output: Ada
console.log(others); // ✅ Expected output: [ 'Linus', 'Grace' ]2️⃣ The Famous One-Line Swap
Before destructuring, swapping two variables needed a temporary third one. Now it's a single, almost self-explanatory line — a favourite in interviews and a genuinely handy trick.
let a = "left";
let b = "right";
// Swap them in one line — no temp variable needed
[a, b] = [b, a];
console.log(a); // ✅ Expected output: right
console.log(b); // ✅ Expected output: left3️⃣ Object Destructuring — Unpack by Name
Use curly braces. The variable name must match the property key. Order does not matter — JavaScript looks up each key by name. This is the form you'll use most often, especially with API data and configuration objects.
const user = {
id: 42,
name: "Jordan",
city: "Lisbon",
};
// Pull out exactly the fields you need (order is irrelevant)
const { name, city } = user;
console.log(name, city); // ✅ Expected output: Jordan Lisbon
// A property that does not exist is simply undefined (no error)
const { email } = user;
console.log(email); // ✅ Expected output: undefined4️⃣ Renaming & Default Values
Two power-ups make object destructuring shine. Rename with key: newName when a property name clashes or is awkward. Add = fallback to supply a default when a value is missing. Remember: the default only kicks in for undefined, not for null or 0.
const settings = { theme: "dark", volume: 0 };
// Rename theme -> mode, and default fontSize to 14 (it's missing)
const { theme: mode, fontSize = 14, volume = 5 } = settings;
console.log(mode); // ✅ Expected output: dark
console.log(fontSize); // ✅ Expected output: 14 (default used: property was undefined)
console.log(volume); // ✅ Expected output: 0 (default NOT used: 0 is a real value)🎯 Your Turn #1 — Pull Out Two Fields
Destructure title and author from the book object.
const book = {
title: "Deep Work",
author: "Cal Newport",
pages: 296,
};
// 👉 replace ___ so you extract title and author by name
const { ___, ___ } = book;
console.log(title); // ✅ Expected output: Deep Work
console.log(author); // ✅ Expected output: Cal Newport5️⃣ Nested Destructuring
Objects often hold other objects. You can reach inside by mirroring the shape of the data. It reads cleanly, but beware: if an intermediate object is missing, you'll get a real error — so add defaults at each level when the data might be incomplete.
const order = {
id: "A-100",
customer: {
name: "Wei",
address: { city: "Taipei", zip: "100" },
},
};
// Mirror the structure to pull city out from two levels deep
const {
customer: {
name,
address: { city },
},
} = order;
console.log(name); // ✅ Expected output: Wei
console.log(city); // ✅ Expected output: Taipei6️⃣ Destructuring Function Parameters
This is where destructuring really pays off. Instead of one positional argument after another, accept a single options object and destructure it in the parameter list — complete with defaults. Callers can pass fields in any order and skip the ones they don't need.
// Accept an options object; default the whole thing to {} so it never crashes
function createUser({ name, role = "member", active = true } = {}) {
return name + " — " + role + " — " + (active ? "active" : "inactive");
}
console.log(createUser({ name: "Sara", role: "admin" })); // ✅ Expected output: Sara — admin — active
console.log(createUser({ name: "Tom" })); // ✅ Expected output: Tom — member — active
console.log(createUser()); // ✅ Expected output: undefined — member — active🎯 Your Turn #2 — Swap Two Values
Use array destructuring to swap x and y in one line.
let x = 1;
let y = 2;
// 👉 replace ___ to swap x and y with destructuring
[x, y] = [___, ___];
console.log(x, y); // ✅ Expected output: 2 1🧩 Reorder Challenge
These lines are scrambled. Reorder them so it logs Mara 90.
Why: the object must exist before you can destructure it, and the variables must exist before you log them.
🧠 Quick Recall
Predict the output before revealing the answer.
0 — defaults only replace undefined. 0 is a real value, so it stays.
y — the leading comma skips the first element, so second grabs the one at index 1.
9 — x: renamed reads property x but stores it in a variable named renamed.
Common Errors & Fixes
- 1️⃣ Using [] for objects or {} for arrays
- 2️⃣ Destructuring null or undefined
- 3️⃣ Forgetting parentheses when assigning to existing vars
- 4️⃣ Going one level too deep into missing data
Quick Reference — Destructuring
| Goal | Syntax |
|---|---|
| Array by position | const [a, b] = arr; |
| Object by name | const { a, b } = obj; |
| Rename | const { a: x } = obj; |
| Default | const { a = 1 } = obj; |
| Rest | const [first, ...rest] = arr; |
| In parameters | function f({ a, b } = {}) {} |
Lesson Complete — Destructuring Assignment!
- ✅ Arrays unpack by position with [ ]
- ✅ Objects unpack by name with { }
- ✅ Rename with key: newName, default with = value
- ✅ Destructure parameters for clean, self-documenting functions
Practice quiz
How are arrays destructured?
- By name with curly braces
- Alphabetically
- By position with square brackets
- By type
Answer: By position with square brackets. Array destructuring uses square brackets and fills variables in order, by position.
How are objects destructured?
- By name with curly braces
- By position with square brackets
- By index
- By value
Answer: By name with curly braces. Object destructuring uses curly braces and matches each variable to a property by name; order does not matter.
Given const { a = 5 } = { a: 0 }, what is a?
- 5
- undefined
- null
- 0
Answer: 0. Defaults only apply when the value is undefined. 0 is a real value, so it stays 0.
What does const [, second] = ["x", "y", "z"] assign to second?
- "x"
- "y"
- "z"
- undefined
Answer: "y". The leading bare comma skips the first element, so second grabs index 1 ('y').
How do you rename a property while destructuring?
- const { name: userName } = u
- const { name => userName } = u
- const { name as userName } = u
- const { userName = name } = u
Answer: const { name: userName } = u. The colon syntax const { name: userName } reads property name into a variable called userName.
What happens when you destructure a property that does not exist on an object?
- It throws a TypeError
- You get null
- You get undefined, no error
- It returns an empty object
Answer: You get undefined, no error. A missing property simply yields undefined; no error is thrown, which is why defaults are useful.
What does const [a, b] = [b, a] accomplish for already-declared a and b?
- It deletes both
- It swaps their values in one line
- It throws an error
- It copies a into b only
Answer: It swaps their values in one line. Array destructuring lets you swap two variables in one line with no temporary variable.
Why default a parameter object: function f({ x } = {})?
- To make x required
- To rename x
- To make x a number
- So calling f() with no argument does not crash on destructuring
Answer: So calling f() with no argument does not crash on destructuring. Defaulting the whole object to {} lets the function be called with no arguments without throwing.
What does const { a } = null throw?
- Nothing, a is undefined
- A TypeError
- A SyntaxError
- A ReferenceError
Answer: A TypeError. Destructuring null or undefined throws a TypeError; guard with a fallback like data || {}.
Given settings = { theme: "dark", volume: 0 } and const { fontSize = 14, volume = 5 } = settings, what is volume?
- 5
- 14
- 0
- undefined
Answer: 0. volume is 0 (a real value), so its default is not used; fontSize would be 14 because it is missing.
Continue this course
- Previous: The this Keyword
- Next: Spread & Rest Operators — Copy, merge and gather with the ... operator
- Quick reference: JavaScript cheat sheet › Arrays
Frequently asked questions
What is the difference between destructuring an array and an object?
Array destructuring is positional — you use square brackets and the order of variables matches the order of elements. Object destructuring is by name — you use curly braces and the variable names must match the property keys (unless you rename them). Position never matters for objects.
Can I rename a property while destructuring an object?
Yes. Use the colon syntax: const { name: userName } = user. This reads the 'name' property but stores it in a variable called userName. It is invaluable when an API key collides with an existing variable or has an awkward name.
How do default values work in destructuring?
Add = value after a variable. The default is used only when the matched value is strictly undefined — not when it is null, 0, or an empty string. So const { count = 10 } = {} gives 10, but const { count = 10 } = { count: 0 } keeps 0.
Why would I destructure inside a function's parameter list?
It lets a function accept an options object while naming exactly the fields it needs, with defaults, right in the signature. function draw({ x = 0, y = 0, color = 'black' } = {}) is self-documenting and lets callers pass arguments in any order.
What happens if I destructure a property that does not exist?
You simply get undefined — no error is thrown. That is why default values are so useful. Be careful with nested destructuring though: trying to read a property of an undefined intermediate object (e.g. const { a: { b } } = {}) WILL throw.