Destructuring
Unpacking Objects & Arrays
LinkedIn Hook
Every codebase has that one function that starts with ten lines of
const x = props.x; const y = props.y; ...before the real logic begins.Destructuring deletes all of that.
In one line you can pull multiple properties out of an object, rename them, give them defaults, reach into nested structures, and collect the rest — all before your function body even starts. The same applies to arrays, including the classic "swap two variables without a temp" one-liner.
But the syntax has sharp edges. Rename with
:, default with=, and if you try to destructure something that'sundefined, you'll throw a TypeError unless you add a default at the right level.In this lesson you'll learn object destructuring, array destructuring, renaming, defaults, nested patterns, and how to use all of these inside function parameters — including the safe pattern for nested destructuring that doesn't blow up at runtime.
Read the full lesson -> [link]
#JavaScript #Destructuring #ES6 #CleanCode #InterviewPrep #Frontend #CodingInterview
What You'll Learn
- Object destructuring with renaming, defaults, and nested patterns
- Array destructuring with skipping, rest, and the swap-without-temp trick
- Destructuring inside function parameters and how to default nested patterns safely
The Suitcase Analogy
Destructuring is like unpacking a suitcase. Instead of reaching into the suitcase every time you need something, you take everything out and place each item where you need it.
Object Destructuring — Basic
const person = { name: "Rakibul", age: 25, city: "Dhaka" };
// Without destructuring
const name1 = person.name;
const age1 = person.age;
// With destructuring
const { name, age, city } = person;
console.log(name); // "Rakibul"
console.log(age); // 25
Renaming Variables
const response = { status: 200, data: "OK", error: null };
// Rename 'data' to 'payload' and 'status' to 'statusCode'
const { status: statusCode, data: payload } = response;
console.log(statusCode); // 200
console.log(payload); // "OK"
// console.log(status); // ReferenceError — 'status' is not defined
Default Values
const config = { theme: "dark" };
const { theme, lang = "en", fontSize = 14 } = config;
console.log(theme); // "dark" (from object)
console.log(lang); // "en" (default — property missing)
console.log(fontSize); // 14 (default — property missing)
// Default + rename combined
const { role: userRole = "viewer" } = {};
console.log(userRole); // "viewer"
Nested Destructuring
const user = {
name: "Rakibul",
address: {
city: "Dhaka",
zip: "1200",
geo: { lat: 23.8, lng: 90.4 }
}
};
const {
name,
address: {
city,
geo: { lat, lng }
}
} = user;
console.log(city); // "Dhaka"
console.log(lat); // 23.8
// console.log(address); // ReferenceError — address is not a variable
Array Destructuring
const colors = ["red", "green", "blue", "yellow", "purple"];
// Basic
const [first, second] = colors;
console.log(first); // "red"
console.log(second); // "green"
// Skip elements
const [, , third] = colors;
console.log(third); // "blue"
// Rest
const [primary, ...others] = colors;
console.log(primary); // "red"
console.log(others); // ["green", "blue", "yellow", "purple"]
// Swap variables (no temp needed!)
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1
Function Parameter Destructuring
// Object destructuring in params
function createUser({ name, role = "user", active = true }) {
return { name, role, active };
}
createUser({ name: "Rakibul" });
// { name: "Rakibul", role: "user", active: true }
// Array destructuring in params
function getFirst([first, ...rest]) {
return { first, remaining: rest.length };
}
getFirst([10, 20, 30]); // { first: 10, remaining: 2 }
// Nested destructuring in params
function printCity({ address: { city } }) {
console.log(city);
}
printCity({ address: { city: "Dhaka" } }); // "Dhaka"
Common Mistakes
- Forgetting that the rename colon goes left-to-right —
const { a: b } = objreads "take propertyaand bind it to variableb", andais no longer accessible. - Nested destructuring a property that might be
undefined—const { address: { city } } = userthrows ifaddressis missing; guard with= {}likeconst { address: { city } = {} } = user. - Putting the same name on both sides of the colon —
const { name: name }is redundant (useconst { name }), andconst { name: newName }is the rename form, not a "copy into itself".
Interview Questions
Q: What happens if you destructure a property that doesn't exist?
It becomes
undefined, unless you provide a default value:const { missing = "default" } = {}.
Q: Can you destructure and rename at the same time?
Yes:
const { originalName: newName } = obj. The colon syntax renames: left side is the source property, right side is the new variable name.
Q: How do you destructure nested objects safely?
You can chain:
const { address: { city } } = user. But ifaddressis undefined, this throws. Use default values:const { address: { city } = {} } = userto prevent runtime errors.
Q: How do you rename a variable during destructuring?
Use the colon syntax:
const { data: payload } = responsetakes thedataproperty and binds it to a new local variable namedpayload. The original namedatais not introduced as a variable.
Q: What does const { a: { b } } = obj do if a is undefined?
It throws a
TypeError: Cannot destructure property 'b' of 'undefined'. To make it safe, supply a default fora:const { a: { b } = {} } = obj, which substitutes an empty object whenaisundefined.
Quick Reference — Cheat Sheet
DESTRUCTURING — QUICK MAP
Object:
const { a, b } = obj basic
const { a: x } = obj rename a -> x
const { a = 1 } = obj default when missing
const { a: x = 1 } = obj rename + default
const { a, ...rest } = obj collect the rest
const { a: { b } = {} } = obj safe nested (default the parent)
Array:
const [a, b] = arr basic
const [ , , c] = arr skip with commas
const [first, ...tail] = arr rest tail
[a, b] = [b, a] swap without temp
Function parameters:
function f({ name, age = 0 }) {} object params with default
function f([head, ...rest]) {} array params
function f({ a: { b } = {} }) {} safe nested params
Rules:
: rename = default ... rest (must be last)
Previous: Spread & Rest Operators -> Same Syntax, Opposite Directions Next: Object Static Methods -> keys, values, entries, freeze, seal
This is Lesson 7.3 of the JavaScript Interview Prep Course — 14 chapters, 87 lessons.