What is destructuring in JavaScript?
Destructuring is a syntax for unpacking values from arrays or properties from objects into separate variables in one step.
Array destructuring — pulls values by position.
Object destructuring — pulls values by property name.
Defaults — provide a fallback when a value is missing.
Renaming — assign a property to a differently named variable.
Nested — unpack deeply nested structures directly.
Everyday uses: reading fields from API responses, swapping variables, and naming function parameters clearly.
// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first, second, rest); // 1, 2, [3, 4, 5]
// Skip elements
const [, , third] = [1, 2, 3];
console.log(third); // 3
// Swap
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b); // 2, 1
// Object destructuring
const user = { name: 'John', age: 30, email: 'john@test.com' };
const { name, age, role = 'user' } = user; // Default value
console.log(name, age, role); // 'John', 30, 'user'
// Rename
const { name: fullName, age: userAge } = user;
console.log(fullName, userAge); // 'John', 30
// Nested
const { address: { city, zip } } = { address: { city: 'NYC', zip: '10001' } };
// Function parameters
function createUser({ name, email, role = 'user' }) {
return { name, email, role };
}
createUser({ name: 'Alice', email: 'alice@test.com' });
// Rest in objects
const { email, ...rest2 } = user;
console.log(rest2); // { name: 'John', age: 30 }Array: [a, b, ...rest] extracts by position. , skips elements. [a, b] = [b, a] swaps. Object: {name, age} extracts by property name. name: fullName renames. role = 'user' provides default.
Nested destructuring reaches into nested objects. ...rest collects remaining properties. Function parameter destructuring extracts specific props from an options object.
Show both array (position-based) and object (name-based). The swap [a, b] = [b, a] is a classic quick trick.
Function parameter destructuring is the most practical daily use. Know renaming (:), defaults (=), and rest (...).