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.
const { a, b } = obj): Matches keys by property name regardless of key order. You can rename variables with const { a: localName } = obj and provide defaults with =.const [first, second] = arr): Matches items by position, skips unwanted items with commas, and swaps two variables in one line ([a, b] = [b, a]).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" });
null or undefined: const { id } = user throws a TypeError if user is null or undefined. Guard with const { id } = user ?? {};.= {} default: Calling printBadge() with no arguments crashes unless you default the parameter to {}.default fallback when the value is null: Destructuring defaults (status = "draft") trigger only when the property is undefined, not when it is null.Yes, write [left, right] = [right, left]; using array destructuring on let variables.
Leave an empty slot before the comma: const [, secondItem] = list;.
No, destructuring only reads values into new variables (or copies remaining keys into a shallow ...rest object/array).
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.