Introduction
Introduced in ECMAScript 2015 (ES6), destructuring assignment provides a concise syntax for extracting values from arrays or properties from objects into distinct variablse. This process essentially involves pattern matching on the source structure and decomposing it to assign values to specific variables.
Array Destructuring
To destructure an array, you use a pattern that mirrors the array syntax on the left side of the assignment.
const sourceArray = [10, 20, 30];
const [first, second, third] = sourceArray;
console.log(first); // 10
console.log(second); // 20
// This is equivalent to:
// const first = sourceArray[0];
// const second = sourceArray[1];
// Partial matching is allowed; unmatched variables are undefined
const [onlyFirst] = sourceArray; // onlyFirst is 10
const [a, b, c, d] = sourceArray; // d is undefined
// You can skip elements using empty commas
const [, middleValue] = sourceArray; // middleValue is 20
// The rest pattern (...) collects remaining elements
const [head, ...remaining] = sourceArray;
console.log(remaining); // [20, 30]
Default values can be specified for cases where the unpacked value is strictly equal to undefined.
// If the index is undefined, the default is used
const [p, q, r, s = 99] = sourceArray; // s defaults to 99
Note: Attempting to destructure a non-iterable value (like a plain object) using aray syntax will throw a TypeError.
Object Destructuring
Object destructuring uses curly braces to match properties by name.
const user = {
username: 'jdoe',
level: 5,
details: {
email: 'jdoe@example.com',
active: true
}
};
const { username, level, details } = user;
console.log(username); // 'jdoe'
console.log(details); // { email: 'jdoe@example.com', active: true }
// Equivalent to:
// const username = user.username;
// const level = user.level;
// If a property does not exist, the result is undefined
const { missingProp } = user; // missingProp is undefined
// Renaming: Use a colon to assign the property to a new variable name
// Here, userLevel is 5, while 'level' variable is not defined
const { level: userLevel } = user;
// Nested destructuring: Access properties within objects
// Avoid naming conflicts; here detailEmail is 'jdoe@example.com'
const { username, details: { email: detailEmail } } = user;
The core mechanism implies that { prop } is shorthand for { prop: prop }.
Like arrays, defaults apply when the property value is strictly undefined.
const { role = 'guest', status = 0 } = { status: 1 };
// role is 'guest', status is 1
String Destructuring
Strings behave like arrays when destructured because they are iterable. You can also destructure object properties of the string wrapper.
const [charA, charB, charC, charD] = 'abcd';
const { length } = 'hello'; // length is 5
Destructuring in Function Parameters
Destructuring can be applied directly to function parameters, allowing for immediate extraction of needed values from the passed argument.
// Destructuring the array argument immediately
function add([x, y]) {
return x + y;
}
console.log(add([7, 8])); // 15
// Practical example with Array.map
const coordinates = [[1, 2], [3, 4]];
const sums = coordinates.map(([x, y]) => x + y);
// sums is [3, 7]