Sub topic 3
Destructuring and Spreading Arrays
This chapter assumes you know let and const, arrow functions, and how to create arrays and read them by index. It covers two related pieces of syntax. Destructuring unpacks array elements into separate variables. Spread (...) expands an array into individual elements wherever a list of values is expected. The same three dots also appear as the rest element, which does the opposite of spread and collects leftover elements into a new array.
Destructuring: Unpacking by Position
A destructuring pattern looks like an array literal on the left side of an assignment. Each variable in the pattern receives the element at the same position.
const point = [10, 20, 30];
const [x, y, z] = point;
console.log(x); // 10
console.log(y); // 20
console.log(z); // 30Matching is by position only. Variable names have no connection to the data. If the pattern has more variables than the array has elements, the extra variables become undefined. If the array has more elements, the extras are ignored.
const [a, b, c] = [1, 2];
console.log(c); // undefined
const [first] = ['only', 'this', 'is', 'kept'];
console.log(first); // 'only'Skipping Elements
To skip a position, leave its slot empty and keep the comma:
const rgb = [255, 128, 0];
const [, green, blue] = rgb;
console.log(green, blue); // 128 0
const [red, , lastValue] = rgb;
console.log(red, lastValue); // 255 0Skipping one or two positions reads fine. When you need to skip more than that, plain indexing such as rgb[5] is usually clearer.
Default Values
A variable in the pattern can take a default value. The default is used only when the value at that position is strictly undefined. That includes missing positions and explicit undefined, but null does not count.
const [width = 100, height = 50] = [300];
console.log(width, height); // 300 50
const [mode = 'light'] = [null];
console.log(mode); // null (null does not trigger the default)Defaults are evaluated lazily, which means the default expression runs only when it is needed:
function fallback() {
console.log('fallback called');
return 0;
}
const [p = fallback()] = [5]; // fallback is not called
const [q = fallback()] = []; // logs 'fallback called'
console.log(p, q); // 5 0A default can also refer to a variable declared earlier in the same pattern:
const [min = 0, max = min + 10] = [];
console.log(min, max); // 0 10The Rest Element
...name placed last in a pattern collects every remaining element into a new array:
const scores = [98, 87, 76, 65];
const [top, ...others] = scores;
console.log(top); // 98
console.log(others); // [87, 76, 65]
const [solo, ...none] = [1];
console.log(none); // [] (always an array, never undefined)The rest element must come last, and no trailing comma is allowed after it. Both const [...front, last] = arr; and const [...all,] = arr; are syntax errors. To get the last element, use arr.at(-1) instead.
Swapping and Reassigning
Destructuring also works with variables that already exist. Without it, swapping two values needs a temporary variable. With it, the swap takes one line:
let left = 'L';
let right = 'R';
[left, right] = [right, left];
console.log(left, right); // 'R' 'L'Nested Patterns and Parameters
Patterns nest to match nested arrays:
const matrix = [[1, 2], [3, 4]];
const [[a11, a12], [a21, a22]] = matrix;
console.log(a11, a22); // 1 4Function parameters can be destructured directly. This works well for functions that receive pairs or tuples:
function distance([x1, y1], [x2, y2]) {
return Math.hypot(x2 - x1, y2 - y1);
}
console.log(distance([0, 0], [3, 4])); // 5Destructuring works on any iterable, not only arrays. That covers strings, Maps, Sets, and generators:
const [ch1, ch2] = 'hi';
console.log(ch1, ch2); // 'h' 'i'
const [[key, value]] = new Map([['lang', 'js']]);
console.log(key, value); // 'lang' 'js'The source has to be iterable, though. Destructuring null or undefined throws a TypeError. This often happens when a function returns nothing:
function getPair() {}
try {
const [m, n] = getPair();
} catch (err) {
console.log(err instanceof TypeError); // true
}
const [m = 0, n = 0] = getPair() ?? [];
console.log(m, n); // 0 0Spread: Expanding an Array
Spread does the reverse of rest. Inside an array literal or a function call, ...arr expands into its individual elements.
In Array Literals
const base = [2, 3];
const extended = [1, ...base, 4];
console.log(extended); // [1, 2, 3, 4]
const merged = [...['a', 'b'], ...['c']];
console.log(merged); // ['a', 'b', 'c']
const copy = [...base];
console.log(copy === base); // false (a new array)Spread also accepts any iterable. A common idiom for removing duplicates is [...new Set(arr)]:
console.log([...new Set([1, 1, 2, 3, 3])]); // [1, 2, 3]
console.log([...'abc']); // ['a', 'b', 'c']In Function Calls
Spread passes array elements as separate arguments:
const temps = [12, 19, 7, 23];
console.log(Math.max(...temps)); // 23
console.log(Math.max(temps)); // NaN (the whole array is one argument)Spread Copies Are Shallow
[...arr] creates a new outer array, but the elements themselves are copied by reference. Nested arrays and objects are still shared between the original and the copy:
const grid = [[1, 2], [3, 4]];
const shallow = [...grid];
shallow.push([5, 6]);
console.log(grid.length); // 2 (the outer array is independent)
shallow[0][0] = 99;
console.log(grid[0][0]); // 99 (the inner array is shared)
const deep = structuredClone(grid);
deep[1][0] = -1;
console.log(grid[1][0]); // 3Use structuredClone when you need a fully independent deep copy. It handles plain data but not functions.
Holes in sparse arrays behave differently under spread. Spread turns each hole into an explicit undefined:
const sparse = [1, , 3];
console.log(1 in sparse); // false (a hole)
console.log(1 in [...sparse]); // true (now holds undefined)Quick Reference
| Syntax | Where it appears | What it does |
|---|---|---|
| `const [a, b] = arr` | Left of `=`, parameters | Unpacks elements by position |
| `const [a = 1] = arr` | Inside a pattern | Default used only for `undefined` |
| `const [a, ...rest] = arr` | Last slot of a pattern | Collects the remaining elements into a new array |
| `[...arr, x]` | Array literal | Expands elements into a new array (shallow copy) |
| `fn(...arr)` | Function call | Passes elements as separate arguments |
Exercise
What does this log, and why? const [a = 'A', b = 'B', ...c] = [undefined, null]; console.log(a, b, c);
Show answer
It logs 'A' null []. Position 0 is undefined, so a takes its default. Position 1 is null, which does not trigger a default, so b is null. No elements remain, so the rest element c is an empty array.
Exercise
Write a function headTail(arr) that returns an object { head, tail }, where head is the first element (or null if the array is empty) and tail is a new array of the remaining elements. Use destructuring in the parameter list.
Show answer
const headTail = ([head = null, ...tail]) => ({ head, tail }); Calling headTail([1, 2, 3]) returns { head: 1, tail: [2, 3] }, and headTail([]) returns { head: null, tail: [] }. Note that an explicit undefined first element would also become null.
Exercise
A teammate writes const backup = [...settings]; and then runs backup[0].theme = 'dark', where settings is an array of objects. Does settings[0].theme change? How would you prevent it?
Show answer
Yes, it changes. Spread makes a shallow copy, so backup[0] and settings[0] are the same object. Use structuredClone(settings), or copy each object with settings.map(s => ({ ...s })) if only one level of nesting matters.