JavaScript Destructuring
Master object and array destructuring for cleaner variable assignment and function parameters.
TL;DR
- 01Extract object properties into variables with curly brace syntax.
- 02Extract array elements into variables with square bracket syntax.
- 03Use default values when properties or elements are missing.
Tips
- 01Use destructuring in function parameters to document what properties a function expects, making code more readable and self-documenting.
- 02Combine destructuring with rest syntax to pull out a few named values while collecting the remaining properties into one object.
- 03Rename destructured variables to avoid naming collisions when two objects in the same scope share a property name.
Warnings
- 01Destructuring doesn't create new properties on objects — it just assigns values to variables in the local scope.
- 02Destructuring a null or undefined value throws a TypeError immediately, so guard against missing data before destructuring it.
- 03Default values only apply when a property is undefined, so a falsy value like false or 0 still wins.
Object Destructuring
Basic extractionExtract properties from an object into separate variables.
const user = { name: "Alice", age: 30 };
const { name, age } = user;
console.log(name); // "Alice"Exact key matchProperty names must match the object keys exactly.
const { name, email } = user;
// name is available, but email is undefinedExtract only what you needDestructure only the properties you need from an object.
const { name } = user;
// age is not extractedRenamingUse shorter or clearer variable names with renaming.
const { name: userName, age: userAge } = user;Nested objectsDestructure nested objects by continuing the pattern.
const user = { profile: { name: "Alice" } };
const { profile: { name } } = user;Array Destructuring
Position-based extractionExtract array elements into separate variables by position.
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
console.log(first); // "red"Skipping elementsSkip elements by leaving the position empty.
const [first, , third] = colors;
// second is not assignedRest syntaxUse rest syntax to capture remaining elements.
const [first, ...rest] = colors;
// first = "red", rest = ["green", "blue"]Nested arraysDestructure nested arrays the same way as nested objects.
const matrix = [[1, 2], [3, 4]];
const [[a, b], [c, d]] = matrix;Swapping variablesSwap variables without a temporary variable.
let x = 1, y = 2;
[x, y] = [y, x]; // x = 2, y = 1Default Values
Basic defaultsProvide default values for properties that might be missing.
const { name = "Guest", email = "no-email" } = {};
console.log(name); // "Guest"Works with arrays tooDefaults work with both objects and arrays.
const [first = "a", second = "b"] = [];
// first = "a", second = "b"Undefined onlyDefaults are used only if the value is undefined, not falsy.
const { count = 0 } = { count: false };
// count = false, not 0Defaults in parametersUse defaults with function parameters for required values.
function greet({ name = "Guest" } = {}) {
console.log(`Hello ${name}`);
}
greet(); // "Hello Guest"Renaming plus defaultsCombine renaming and defaults in one destructuring expression.
const { name: userName = "Anonymous", age: userAge = 0 } = {};
console.log(userName); // "Anonymous"
console.log(userAge); // 0Function Parameters
Destructured object paramsDestructure objects directly in function parameters.
function displayUser({ name, age }) {
console.log(`${name} is ${age}`);
}
displayUser({ name: "Alice", age: 30 });Destructured array paramsDestructure arrays in function parameters the same way.
function sum([a, b]) {
return a + b;
}
sum([1, 2]); // 3Default paramsUse default parameters together with destructuring.
function greet({ greeting = "Hello" } = {}) {
console.log(greeting);
}
greet(); // "Hello"Self-documentingThis pattern makes function signatures self-documenting.
Shape validationDestructuring in parameters forces the caller's data to have the expected shape.
Advanced Patterns
Computed property namesExtract a property using a dynamic key with computed property names.
const key = "name";
const { [key]: value } = { name: "Alice" };Collect remaining propertiesExtract named properties and collect the rest into a new object.
const { name, ...rest } = { name: "Alice", age: 30, city: "NYC" };
// rest = { age: 30, city: "NYC" }Rename plus defaultsRename multiple properties and set defaults in the same pattern.
const { name: n = "Guest", age: a = 0 } = user;Deeply nested aliasesDestructure deeply nested paths with renaming in a single expression.
const {
profile: {
contact: { email }
}
} = user;In Practice
Nested destructuring, renaming, and defaults pull exactly the fields needed from a server response in one expression.
- 01The outer pattern reaches into data, then into user and settings, without intermediate variables.
- 02name: userName renames the nested property while role = 'guest' supplies a fallback if it's missing.
- 03settings: { theme = 'light' } = {} guards against settings itself being undefined.
- 04...meta collects every top-level property not already destructured, here just status.
const response = {
status: 200,
data: {
user: { id: 7, name: 'Priya', role: 'admin' },
settings: { theme: 'dark' }
}
};
const {
data: {
user: { name: userName, role = 'guest' },
settings: { theme = 'light' } = {}
},
...meta
} = response;
console.log(userName, role, theme); // "Priya" "admin" "dark"
console.log(meta); // { status: 200 }FAQ
Use the colon syntax: const { name: firstName } = user assigns the name property to a variable called firstName. This lets you avoid naming conflicts or clarify intent without modifying the original object.
Yes — chain the syntax: const { address: { city } } = user extracts city from a nested object. Be careful with deep nesting. It throws if an intermediate property is null or undefined.
Array destructuring uses square brackets and assigns by position, like const [first, second] = arr. Object destructuring uses curly braces and assigns by property name instead. Use array destructuring when order matters, object destructuring when keys matter.
Leave a blank space with a comma: const [, second, , fourth] = arr skips the first and third elements. Each comma advances the position without creating a variable.
This usually means there's a typo in the property name — destructuring is case-sensitive and must match the exact key. Use default values, like const { count = 0 } = obj, to guard against missing or undefined properties.