Sub topic 1
Unpacking Arrays by Position
Array destructuring lets you pull values out of an array and into separate variables in one statement. You write a pattern that looks like an array literal on the left side of =, and JavaScript fills each variable from the matching position on the right side. This chapter covers the core model: how positions are matched, what happens when the counts don't line up, how to skip elements, and which errors come up most often.
Prerequisites
This chapter assumes you are comfortable with:
- Declaring variables with
letandconst - Creating and indexing arrays (
arr[0],arr.length) - Writing and calling functions, including arrow functions
- The difference between primitive values and references to objects
You do not need any prior experience with destructuring.
The Basic Pattern
Without destructuring, you read each element by index:
const colors = ['red', 'green', 'blue'];
const primary = colors[0];
const secondary = colors[1];
const tertiary = colors[2];
console.log(primary, secondary, tertiary); // red green blueWith destructuring, one declaration does the same work:
const colors = ['red', 'green', 'blue'];
const [primary, secondary, tertiary] = colors;
console.log(primary); // 'red'
console.log(secondary); // 'green'
console.log(tertiary); // 'blue'The brackets on the left are not an array. They form a binding pattern, a template that describes where each value should go. The first name gets the element at index 0, the second gets index 1, and so on. The names don't matter. Only their positions do.
The source array is not changed. Destructuring reads values and copies them into new bindings. If an element is an object, the variable receives a reference to that same object, the same way const x = arr[0] would.
`const` and `let` both work
The pattern follows the rules of whichever keyword declares it. With const, none of the variables can be reassigned. With let, all of them can.
let [count, label] = [3, 'items'];
count += 1;
console.log(count, label); // 4 'items'A declaration pattern always needs a right-hand side. const [a, b]; is a SyntaxError, because there is nothing to destructure.
When the Counts Don't Match
The pattern and the array do not need the same length. JavaScript handles a mismatch in either direction without an error.
Fewer variables than elements
Extra elements are ignored:
const scores = [98, 87, 76, 65];
const [best, runnerUp] = scores;
console.log(best, runnerUp); // 98 87More variables than elements
Variables with no matching element get undefined:
const pair = ['x', 'y'];
const [first, second, third] = pair;
console.log(third); // undefinedThis silent undefined is a common cause of bugs further down the line. If a value might be missing, give it a default. Defaults are covered in the "Supplying Default Values" chapter.
| Pattern | Source | Result |
|---|---|---|
| `[a, b]` | `[1, 2, 3]` | `a = 1`, `b = 2`, `3` ignored |
| `[a, b, c]` | `[1, 2]` | `a = 1`, `b = 2`, `c = undefined` |
| `[a]` | `[]` | `a = undefined` |
| `[a, b]` | `[, 2]` (sparse) | `a = undefined`, `b = 2` |
The last row shows that a hole in a sparse array also produces undefined. Destructuring cannot tell a hole apart from an element that is explicitly undefined.
Skipping Elements
To skip a position, leave its slot empty and keep the comma. Each comma moves you forward one index.
const date = ['2026', '11', '24'];
const [, month] = date;
console.log(month); // '11'
const [year, , day] = date;
console.log(year, day); // '2026' '24'
const [, , onlyDay] = date;
console.log(onlyDay); // '24'Empty slots are easy to misread when there are several in a row. [, , , d] takes index 3, but a reader has to count commas to see that. If you need an element deep in a long array, plain indexing (arr[3]) is often clearer.
A trailing comma at the end of a pattern does nothing: const [a, b,] = arr is the same as const [a, b] = arr.
Where Array Destructuring Earns Its Keep
Returning several values from a function
A function can return only one value, but that value can be an array. The caller then unpacks it by position.
function divide(dividend, divisor) {
const quotient = Math.floor(dividend / divisor);
const remainder = dividend % divisor;
return [quotient, remainder];
}
const [q, r] = divide(17, 5);
console.log(q, r); // 3 2This works well when the order is obvious and there are only two or three values. With more values, or when the order is arbitrary, return an object instead so callers match by name (see "Unpacking Objects by Property Name").
Splitting strings
String.prototype.split returns an array, so you can name the parts directly:
const [hours, minutes] = '09:45'.split(':');
console.log(hours, minutes); // '09' '45'Regular expression matches
RegExp.prototype.exec returns an array where index 0 is the whole match and later indexes are capture groups. Skipping index 0 is a common idiom:
const match = /(\d{4})-(\d{2})-(\d{2})/.exec('Due: 2026-11-24');
const [, y, m, d] = match;
console.log(y, m, d); // '2026' '11' '24'Looping over index–value pairs
Array.prototype.entries() yields [index, value] pairs, and a for...of loop can destructure each pair:
const fruits = ['apple', 'pear', 'plum'];
for (const [index, fruit] of fruits.entries()) {
console.log(`${index}: ${fruit}`);
}
// 0: apple
// 1: pear
// 2: plumHow It Works Underneath
Array destructuring does not read arr[0], arr[1], and so on. It uses the iteration protocol. JavaScript calls the source's [Symbol.iterator]() method and then calls next() once for each position in the pattern. This has two consequences.
First, values are pulled lazily. JavaScript requests only as many values as the pattern needs, so destructuring an endless generator is safe:
function* naturals() {
let n = 0;
while (true) {
console.log(`producing ${n}`);
yield n++;
}
}
const [zero, one] = naturals();
// producing 0
// producing 1
console.log(zero, one); // 0 1Second, the source must be iterable. Any iterable works, including strings, Sets, and Maps, which a later chapter covers. A value that is not iterable throws a TypeError, even if it looks like an array.
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
try {
const [first] = arrayLike;
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // e.g. "arrayLike is not iterable"
}If you need to destructure an array-like object, convert it first with Array.from(arrayLike).
Common Errors
const result = /(\d+)/.exec('no digits here');
if (result) {
const [, digits] = result;
console.log(digits);
} else {
console.log('no match'); // this branch runs
}Other mistakes to watch for:
- Off-by-one skipping.
[, second]takes index 1, not index 2. Count the commas before the name: each one skips a slot. - Assuming order in unordered data. Destructuring an array built from an object's keys or from a database query with no
ORDER BYgives you whatever order the source produced, which may not be the order you expect. - Confusing patterns with literals.
const [a, b] = ...declares two variables. It does not create an array named[a, b]. - Destructuring an object as an array.
const [name] = { name: 'Ada' }throws because plain objects are not iterable. Use an object pattern with braces instead.
Summary
- Array destructuring matches by position, using a pattern of names in brackets.
- Extra elements are ignored, and missing elements become
undefined. - Empty slots between commas skip elements.
- The source is read through the iteration protocol, lazily and one value per slot.
- Non-iterable values, including
null,undefined, and plain objects, throw aTypeError.
Exercise
What does this code log? const [a, , b, c] = ['w', 'x', 'y']; console.log(a, b, c);
Show answer
It logs w y undefined. a takes index 0 ('w'), the empty slot skips index 1 ('x'), b takes index 2 ('y'), and c has no element at index 3, so it is undefined.
Exercise
A function parseVersion(str) should return the major and minor numbers from a string like "4.12.0". Write it so a caller can write const [major, minor] = parseVersion('4.12.0') and get the numbers 4 and 12.
Show answer
function parseVersion(str) { const [major, minor] = str.split('.'); return [Number(major), Number(minor)]; }. split('.') gives ['4', '12', '0'], the pattern takes the first two strings and ignores the patch part, and Number converts them before they are returned as a two-element array.
Exercise
Why does const [first] = document.querySelectorAll('p'); work in a browser, but const [first] = { 0: 'p', length: 1 }; throws?
Show answer
Array destructuring needs an iterable. NodeList (the return value of querySelectorAll) implements Symbol.iterator, so it can be destructured. The plain object has indexes and a length but no Symbol.iterator method, so JavaScript throws a TypeError saying it is not iterable. Wrapping it in Array.from(...) fixes the problem.