Sub topic 1
Unpacking Arrays by Position
Destructuring is syntax that pulls values out of an array or object and stores them in variables in one statement. This chapter covers the two basic pattern forms: defaults, renaming, and rest.
Prerequisites
This chapter assumes you can:
- Declare variables with
letandconst - Work with arrays and plain objects
- Write and call functions, including arrow functions
- Tell reference values apart from primitive values
Unpacking Arrays by Position
An array pattern assigns values by index. Leave an empty slot between commas to skip an element.
const [first, , third] = ['a', 'b', 'c'];
console.log(first); // 'a'
console.log(third); // 'c'A common mistake is assuming the variable names matter here. Only position counts.
Unpacking Objects by Property Name
An object pattern matches by property name, so order does not matter. A name with no matching property gets undefined and does not throw an error.
const user = { name: 'Ada', id: 7 };
const { id, name, email } = user;
console.log(name, id, email); // 'Ada' 7 undefinedSupplying Default Values
Write = value after a target. The default is used only when the extracted value is undefined.
const [x = 1, y = 2] = [10, undefined];
console.log(x, y); // 10 2
const { role = 'guest' } = {};
console.log(role); // 'guest'Renaming Properties as You Destructure
The syntax property: newName reads a property and stores it under a different variable name. You can add a default after the new name.
const user = { name: 'Ada', id: 7 };
const { name: userName, role: userRole = 'guest' } = user;
console.log(userName, userRole); // 'Ada' 'guest'The name on the left side of the colon is the property, and the name on the right is the variable. Writing them the other way round is a frequent error.
Collecting the Rest in Patterns
A rest element (...name) must come last in the pattern. In an array pattern it gathers the remaining elements into a new array. In an object pattern it gathers the remaining own enumerable properties into a new object.
const [head, ...tail] = [1, 2, 3, 4];
console.log(head, tail); // 1 [2, 3, 4]
const { name, ...rest } = { name: 'Ada', id: 7, active: true };
console.log(rest); // { id: 7, active: true }Exercise
What does this log? const [a, , b = 'z', ...c] = ['p', 'q', undefined, 'r', 's']; console.log(a, b, c);
Show answer
It logs 'p' 'z' ['r', 's']. The empty slot skips 'q'. The third value is undefined, so b takes its default 'z'. The rest element collects the remaining elements, 'r' and 's'.
Exercise
Write one statement that reads the property title from book into a variable named heading, with the default 'Untitled'.
Show answer
const { title: heading = 'Untitled' } = book;