Syntax
const { prop } = object;
const [first, second] = array;Examples
Object Destructuring
Extracting object properties into variables, including renaming and defaults.
const user = { name: "Alice", age: 25, city: "London" };
const { name, age } = user;
console.log(name, age); // "Alice" 25
// Renaming while destructuring
const { name: userName } = user;
console.log(userName); // "Alice"
// Default values for missing properties
const { country = "Unknown" } = user;
console.log(country); // "Unknown"Array Destructuring
Extracting array elements by position.
const colors = ["red", "green", "blue"];
const [first, second] = colors;
console.log(first, second); // "red" "green"
// Skipping elements
const [, , third] = colors;
console.log(third); // "blue"
// Swapping variables in one line
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1Destructuring Function Parameters
A very common pattern - destructuring directly in a function signature.
function displayUser({ name, age }) {
console.log(`${name} is ${age} years old`);
}
displayUser({ name: "Bob", age: 30, city: "Leeds" });
// city is ignored - only name and age are pulled outBest practices
- Use destructuring for function parameters that are objects - it documents exactly what properties the function relies on
- Provide default values during destructuring instead of separate fallback checks afterward
- Use nested destructuring sparingly - beyond two levels it often becomes harder to read than explicit access
- Combine with rest syntax (const { a, ...rest } = obj) to pull out specific properties and keep the remainder together
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification