JS Destructuring
JavaScript Destructuring: Unpacking Objects and Arrays
JavaScript destructuring assignment extracts properties from objects or items from arrays into distinct variables in one clean expression. Introduced in ES6, it reduces repetitive user.profile.name lookups and makes function signatures self-documenting.
Object and Array Destructuring Basics
- Object destructuring (
const { a, b } = obj): Matches keys by property name regardless of key order. You can rename variables withconst { a: localName } = objand provide defaults with=. - Array destructuring (
const [first, second] = arr): Matches items by position, skips unwanted items with commas, and swaps two variables in one line ([a, b] = [b, a]).
Practical Destructuring in Functions and Rest Patterns
Combine destructuring with ...rest to separate known fields from remaining properties or tail elements.
const apiResponse = {
id: 88,
title: "ES6 Guide",
author: { name: "Tariq" },
};
// Rename, nested destructuring, and default value
const {
title: lessonTitle,
status = "published",
author: { name: authorName },
} = apiResponse;
console.log({ lessonTitle, status, authorName });
// Array destructuring with rest
const [winner, runnerUp, ...others] = ["Ada", "Linus", "Grace", "Alan"];
console.log({ winner, runnerUp, others });
// Function parameter destructuring with default empty object
function printBadge({ name, role = "member" } = {}) {
console.log(`${name} [${role}]`);
}
printBadge({ name: "Nadia" });
Common Mistakes to Avoid
- Destructuring
nullorundefined:const { id } = userthrows aTypeErrorifuserisnullorundefined. Guard withconst { id } = user ?? {};. - Passing an object argument without
= {}default: CallingprintBadge()with no arguments crashes unless you default the parameter to{}. - Using
defaultfallback when the value isnull: Destructuring defaults (status = "draft") trigger only when the property isundefined, not when it isnull.
Frequently Asked Questions
Can I swap two variables without a temporary variable?
Yes, write [left, right] = [right, left]; using array destructuring on let variables.
How do I ignore the first element of an array when destructuring?
Leave an empty slot before the comma: const [, secondItem] = list;.
Does destructuring mutate the original object or array?
No, destructuring only reads values into new variables (or copies remaining keys into a shallow ...rest object/array).
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.