Sub topic 12
Assigning to Existing Variables and Swapping Values
So far, every pattern in this tutorial has appeared in a declaration, such as const [a, b] = ... or let { x } = .... Patterns also work in plain assignment, where they write into variables that already exist. That form is called destructuring assignment. It lets you swap values without a temporary variable, update several variables in one step, and write directly into object properties or array slots.
This chapter assumes you know let and const, array and object destructuring with defaults and renaming, and the difference between a statement and an expression.
Declaration Patterns vs Assignment Patterns
A declaration pattern creates new bindings. An assignment pattern reuses bindings, or any other valid assignment target, that already exist.
let first;
let second;
[first, second] = ['red', 'green'];
console.log(first, second); // 'red' 'green'
[first = 'none', , second] = [undefined, 'skip', 'blue'];
console.log(first, second); // 'none' 'blue'Defaults, skipped slots, renaming, and rest all behave as they do in declarations. The differences are in what can appear on the left side and how the parser reads the statement.
| Aspect | Declaration (`const`/`let`) | Assignment (no keyword) |
|---|---|---|
| Creates new variables | Yes | No |
| Targets allowed | Identifiers only | Any assignment target: variables, `obj.prop`, `arr[i]` |
| Object pattern at statement start | Fine | Needs wrapping parentheses |
| Works with `const` variables | Declares them | Throws `TypeError` |
| Undeclared names | Declared by the statement | `ReferenceError` in strict mode and modules |
Writing into Properties and Array Elements
In a declaration, each target must be a plain name. In an assignment, a target can be any expression you could put on the left of =. That includes member expressions.
const point = { x: 0, y: 0 };
const coords = [5, 8];
[point.x, point.y] = coords;
console.log(point); // { x: 5, y: 8 }
const target = {};
({ width: target.w, height: target.h = 100 } = { width: 640 });
console.log(target); // { w: 640, h: 100 }
const slots = [];
[slots[0], ...slots[1]] = 'abc';
console.log(slots); // ['a', ['b', 'c']]In the object pattern { width: target.w }, the part before the colon names the source property, and the part after the colon is the place the value is written to. This is the same rename syntax from earlier chapters, with a property in place of a new variable name.
A rest target can also be a member expression, as slots[1] shows. The rest element must still come last in the pattern.
Swapping Without a Temporary Variable
The classic swap needs a third variable:
let a = 1;
let b = 2;
const temp = a;
a = b;
b = temp;
console.log(a, b); // 2 1Destructuring assignment does the same thing in one line:
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1The swap works because of evaluation order. The engine evaluates the right-hand side completely before it assigns anything. [b, a] builds a new array holding the current values, [2, 1]. Only after that does the pattern on the left read from the array and assign to a, then b.
The temporary array is still there. It is just unnamed. Modern engines optimize this pattern well, so readability is usually the better reason to choose one form over the other.
Rotating and Stepping Values
The same idea extends to any number of variables, and the right side can contain expressions computed from the old values:
let x = 1, y = 2, z = 3;
[x, y, z] = [y, z, x];
console.log(x, y, z); // 2 3 1
let prev = 0, curr = 1;
for (let i = 0; i < 5; i++) {
[prev, curr] = [curr, prev + curr];
}
console.log(prev, curr); // 5 8In the Fibonacci loop, prev + curr is computed from the old values, because the right side is finished before either variable changes.
Swapping Array Elements
Member targets make in-place element swaps short, which helps in sorting and shuffling code:
function swap(arr, i, j) {
[arr[i], arr[j]] = [arr[j], arr[i]];
return arr;
}
console.log(swap(['a', 'b', 'c'], 0, 2)); // ['c', 'b', 'a']Gotcha: Targets Are Evaluated Left to Right
The right side is fully evaluated first. The left-side targets are not. Each target's reference is worked out just before the value is assigned to it, in order from left to right. If a later target depends on a variable that an earlier target changes, it sees the new value.
const arr = [10, 20, 30];
let i = 0;
[i, arr[i]] = [2, 99];
console.log(i); // 2
console.log(arr); // [10, 20, 99] (arr[2] changed, not arr[0])You might expect arr[0] to become 99. However, i was already 2 when arr[i] was evaluated. When targets depend on each other, write separate statements or capture the index first.
Parsing Pitfalls
Object Patterns Need Parentheses
When a statement begins with {, JavaScript parses it as a block. A bare object pattern is therefore a syntax error:
let width, height;
// { width, height } = { width: 3, height: 4 }; // SyntaxError
({ width, height } = { width: 3, height: 4 });
console.log(width, height); // 3 4The parentheses make the parser treat the line as an expression. Array patterns do not need them, because a statement starting with [ is already an expression.
Missing Semicolons
If you omit semicolons, a line that starts with [ or ( continues the previous line. That breaks both forms of destructuring assignment:
let a = 1
let b = 2
;[a, b] = [b, a] // leading semicolon prevents "2[a, b] = ..."
console.log(a, b) // 2 1Without the leading ;, the engine reads let b = 2[a, b] = [b, a]. That evaluates b while it is still uninitialized and throws a ReferenceError. The same thing happens with ({ x } = obj) after a line such as doSomething(): the parenthesized expression is parsed as a call on the previous line's result. Codebases written without semicolons usually put a defensive ; before such lines. Formatters like Prettier insert it automatically.
`const` and Undeclared Targets
'use strict';
const locked = 1;
try {
[locked] = [2];
} catch (err) {
console.log(err instanceof TypeError); // true
}
try {
[notDeclared] = [3];
} catch (err) {
console.log(err instanceof ReferenceError); // true
}Outside strict mode, assigning to an undeclared name creates an accidental global. ES modules and classes are always strict, so in modern code you get the ReferenceError.
The Expression's Value and Practical Uses
A destructuring assignment is an expression. Its value is the whole right-hand side, not the values extracted from it:
let a, b;
const result = ([a, b] = [1, 2, 3]);
console.log(a, b); // 1 2
console.log(result); // [1, 2, 3]That makes chaining possible, though it is rarely clearer than two statements. More useful applications include unpacking regex matches into existing variables and reusing loop variables:
let year, month;
[, year, month] = /(\d{4})-(\d{2})/.exec('2026-11');
console.log(year, month); // '2026' '11'
const ages = new Map([['ann', 31], ['bo', 27]]);
let name, age;
for ([name, age] of ages) {
// name and age are reassigned each iteration
}
console.log(name, age); // 'bo' 27The leading empty slot in [, year, month] skips index 0, which holds the full match. If exec returns null, the assignment throws a TypeError, as any destructuring of null does. Guard the call when a failed match is possible.
Exercise
Given let lo = 9, hi = 3;, write one statement that puts the smaller value in lo and the larger in hi whatever their starting order, using destructuring assignment.
Show answer
[lo, hi] = [Math.min(lo, hi), Math.max(lo, hi)]; The right side is computed from the original values before either variable is assigned, so afterward lo is 3 and hi is 9.
Exercise
What does this log, and why? const box = { n: 0 }; let key; ({ k: key, v: box[key] } = { k: 'n', v: 42 }); console.log(box);
Show answer
It logs { n: 42 }. The targets are evaluated left to right, so key is assigned 'n' before the expression box[key] is evaluated. That expression then refers to box.n, which receives 42.
Exercise
A codebase without semicolons has the lines const total = compute() followed by ({ count } = stats). What goes wrong, and how do you fix it?
Show answer
The second line is parsed as a call: compute()({ count } = stats). It tries to call the return value of compute() with the assignment result, which usually throws a TypeError. Fix it with a leading semicolon, ;({ count } = stats), or by ending the previous line with a semicolon.