ES6+beginner
Array Destructuring
Unpacking values from arrays into individual variables by position, including skipping elements, defaults, and swapping variables.
Array destructuring unpacks by position.
Array destructuring is like handing out lottery tickets in the order people are standing in line — position is all that matters, and you can wave someone through without a ticket (skipping an element) if you want.
Key Concepts
1
const [a, b] = [1, 2];
const [x, , z] = [1, 2, 3]; // skip with a comma
const [p, ...rest] = [1, 2, 3]; // rest
const [q = 10] = []; // default -- q is 102
Defaults apply only to undefined.
const [a = 1] = [null]; // a is null, not 1undefined
3
Swapping needs no temporary.
[a, b] = [b, a];4
It works on any iterable, not just arrays:
5
const [first, second] = 'hi'; // 'h', 'i'
const [a, b] = new Set([1, 2]);
const [x, y] = new Map([['a',1],['b',2]]); // entry pairs6
Which is why iterating a Map reads well.
for (const [key, value] of map) { }
for (const [key, value] of Object.entries(obj)) { }7
Nested patterns follow the structure.
const [[a, b], [c]] = [[1, 2], [3]];
const [{ name }] = users; // first user's name8
Function returns are the common use.
function useState(initial) { return [value, setValue]; }
const [count, setCount] = useState(0);9
React's hooks return arrays precisely so the caller names both parts, which an object would also allow —
with the difference that an array lets the names be anything, and an object would fix them.
10
Against object destructuring.
array by position -- order matters, names are yours
object by name -- order irrelevant, names must match11
Use an array when the values have a natural order and the caller should name them. Use an object when there
are several values and position would be arbitrary.
12
The caution: a missing value is undefined, not an error.
const [a, b, c] = [1]; // b and c are undefinedundefined
13
Destructuring more elements than exist fails silently, which is fine with defaults and a source of confusion
without them.
14
And destructuring null throws.
const [a] = null; // TypeErrornull
15
Guard with a default on the whole thing: const [a] = arr ?? [].
const [a] = arr ?? []
16
What the interviewer is probing.1. "How do you skip an element?" Probing: the syntax. Stalls: "You cannot." Moves up:
leave a hole: const [, second] = arr.
17
2. "How do you swap two variables?" Probing: the idiom. Stalls: "With a temp." Moves up:
[a, b] = [b, a].
18
3. "What does a rest element capture?" Probing: the behaviour. Stalls: "One value." *Moves
up:* everything remaining as a new array, and it must be last.
19
4. "When does a default apply?" Probing: the trigger. Stalls: "For missing or null." *Moves
up:* only for undefined, so a null element keeps null.