JavaScript Array Destructuring: Complete Tutorial
Master JavaScript array destructuring for extracting values into variables. Covers syntax, default values, skipping elements, rest pattern, swapping variables, nested destructuring, function parameters, and common mistakes.
Array destructuring lets you extract values from an array and assign them to variables in a single statement. Instead of accessing elements by index (arr[0], arr[1]), you write const [first, second] = arr and get named variables immediately. Introduced in ES6, destructuring makes code shorter, clearer, and eliminates the need for temporary index-based access.
What Array Destructuring Does
// Without destructuring
const coordinates = [40.7128, -74.0060];
const lat = coordinates[0];
const lng = coordinates[1];
// With destructuring
const [latitude, longitude] = [40.7128, -74.0060];
console.log(latitude); // 40.7128
console.log(longitude); // -74.0060The variable names on the left map to array positions on the right, in order.
Basic Syntax
const colors = ["red", "green", "blue", "yellow", "purple"];
const [first, second, third] = colors;
console.log(first); // "red"
console.log(second); // "green"
console.log(third); // "blue"
// "yellow" and "purple" are not assigned to anythingDestructuring works with let and var as well:
let [x, y] = [10, 20];
x = 30; // Reassignable with let
const [a, b] = [10, 20];
// a = 30; // TypeError with constSkipping Elements
Leave gaps in the destructuring pattern to skip positions:
const rgb = [255, 128, 0];
// Skip the green channel
const [red, , blue] = rgb;
console.log(red); // 255
console.log(blue); // 0
// Skip first two elements
const [, , blueOnly] = rgb;
console.log(blueOnly); // 0Default Values
When the array has fewer elements than the pattern, missing positions default to undefined. You can assign fallback values:
const partial = [1, 2];
// Without defaults
const [a, b, c] = partial;
console.log(c); // undefined
// With defaults
const [x, y, z = 0] = partial;
console.log(z); // 0
// Default is only used when the value is undefined (not null or 0)
const [p = 10, q = 20] = [null, 0];
console.log(p); // null (not 10, because null !== undefined)
console.log(q); // 0 (not 20, because 0 !== undefined)Defaults Only Replace undefined
Default values activate only when the destructured position is exactly undefined. Values like null, 0, false, and "" are valid and will NOT be replaced by defaults. This catches beginners who expect defaults to replace all falsy values.
Rest Pattern (...rest)
The rest element collects all remaining elements into a new array. It uses the spread operator syntax (...) and must be the last element in the pattern:
const scores = [95, 88, 72, 91, 84, 67];
const [highest, secondHighest, ...remaining] = scores;
console.log(highest); // 95
console.log(secondHighest); // 88
console.log(remaining); // [72, 91, 84, 67]Head and Tail Pattern
const items = ["first", "second", "third", "fourth"];
const [head, ...tail] = items;
console.log(head); // "first"
console.log(tail); // ["second", "third", "fourth"]Rest with Empty Remaining
const pair = [1, 2];
const [a, b, ...rest] = pair;
console.log(rest); // [] (empty array, not undefined)Swapping Variables
Destructuring enables one-line variable swaps without a temporary variable:
let a = 1;
let b = 2;
// Traditional swap (needs temp variable)
// const temp = a; a = b; b = temp;
// Destructuring swap
[a, b] = [b, a];
console.log(a); // 2
console.log(b); // 1This works with any number of variables:
let x = 1, y = 2, z = 3;
[x, y, z] = [z, x, y];
console.log(x, y, z); // 3 1 2Nested Destructuring
Destructure arrays inside arrays by nesting the pattern:
const matrix = [[1, 2], [3, 4], [5, 6]];
const [[a, b], [c, d], [e, f]] = matrix;
console.log(a, b); // 1 2
console.log(c, d); // 3 4
console.log(e, f); // 5 6Partial Nested Extraction
const data = [1, [2, 3, 4], 5];
const [first, [, middle], last] = data;
console.log(first); // 1
console.log(middle); // 3
console.log(last); // 5Deep Nesting
const response = [200, ["success", [{ userId: 42, name: "Alice" }]]];
const [status, [message, [user]]] = response;
console.log(status); // 200
console.log(message); // "success"
console.log(user.name); // "Alice"Destructuring Function Return Values
Functions that return arrays become much more ergonomic with destructuring:
function getMinMax(numbers) {
const sorted = [...numbers].sort((a, b) => a - b);
return [sorted[0], sorted[sorted.length - 1]];
}
const [min, max] = getMinMax([42, 7, 19, 3, 88]);
console.log(min); // 3
console.log(max); // 88Ignoring Return Values
function getMetadata() {
return ["2026-03-05", "article", "published", 4523];
}
// Only need the date and word count
const [date, , , wordCount] = getMetadata();
console.log(date); // "2026-03-05"
console.log(wordCount); // 4523Destructuring in Function Parameters
Accept array arguments and destructure them directly in the parameter list:
function formatPoint([x, y]) {
return `(${x}, ${y})`;
}
console.log(formatPoint([10, 20])); // "(10, 20)"
// With defaults
function createRange([start = 0, end = 100] = []) {
return { start, end };
}
console.log(createRange([5, 50])); // { start: 5, end: 50 }
console.log(createRange()); // { start: 0, end: 100 }Destructuring in forEach and map
const coordinates = [[40.7128, -74.0060], [34.0522, -118.2437], [51.5074, -0.1278]];
coordinates.forEach(([lat, lng]) => {
console.log(`Latitude: ${lat}, Longitude: ${lng}`);
});
const labels = coordinates.map(([lat, lng]) => `${lat}N, ${Math.abs(lng)}W`);
console.log(labels); // ["40.7128N, 74.006W", "34.0522N, 118.2437W", "51.5074N, 0.1278W"]Destructuring with Iterables
Destructuring works with any iterable, not just arrays:
// String
const [first, second, third] = "hello";
console.log(first, second, third); // "h" "e" "l"
// Set
const [a, b] = new Set([10, 20, 30]);
console.log(a, b); // 10 20
// Map entries
const map = new Map([["name", "Alice"], ["role", "admin"]]);
const [[key1, val1], [key2, val2]] = map;
console.log(key1, val1); // "name" "Alice"
console.log(key2, val2); // "role" "admin"Destructuring with Regular Expressions
String.prototype.match() returns an array, making destructuring a clean way to extract capture groups:
const dateStr = "2026-03-05";
const [, year, month, day] = dateStr.match(/(\d{4})-(\d{2})-(\d{2})/);
console.log(year); // "2026"
console.log(month); // "03"
console.log(day); // "05"The first position is skipped because match() returns the full match at index 0.
Common Mistakes
Destructuring undefined or null:
// TypeError: Cannot destructure property of undefined
// const [a, b] = undefined;
// const [x, y] = null;
// Fix: provide a default
const [a = 0, b = 0] = undefined ?? [];
console.log(a, b); // 0 0
// Or guard with a conditional
function process(maybeArray) {
if (!Array.isArray(maybeArray)) return;
const [first, second] = maybeArray;
console.log(first, second);
}Forgetting rest must be last:
// SyntaxError: Rest element must be last element
// const [...rest, last] = [1, 2, 3];
// Fix: rest must be at the end
const [first, ...rest] = [1, 2, 3];
console.log(first); // 1
console.log(rest); // [2, 3]Confusing array and object destructuring:
const obj = { a: 1, b: 2 };
// Bug: using array destructuring on an object
// const [a, b] = obj; // TypeError: obj is not iterable
// Fix: use object destructuring (curly braces)
const { a, b } = obj;
console.log(a, b); // 1 2Missing parentheses in assignment destructuring:
let a, b;
// SyntaxError: the { looks like a block statement
// [a, b] = [1, 2]; // This actually works for arrays
// But for reassignment with a leading [ on a new line,
// be aware of automatic semicolon insertion:
const arr = [1, 2];
// If on a new line after an expression, it might be parsed as property access
// Semicolons prevent this ambiguity
;[a, b] = arr;
console.log(a, b); // 1 2Over-destructuring:
const pair = [1, 2];
// Extracting more than exists
const [a, b, c, d] = pair;
console.log(c); // undefined
console.log(d); // undefined
// Use defaults when extra positions are possible
const [x, y, z = 0, w = 0] = pair;
console.log(z); // 0Best Practices
- Use meaningful variable names.
const [lat, lng] = coordsis far clearer thanconst [a, b] = coords. - Provide defaults for optional positions. When the array might have fewer elements than expected, set defaults to avoid
undefined. - Use rest for variable-length arrays.
const [head, ...tail]is the standard pattern for processing the first element differently. - Destructure in function parameters. When a function receives an array, destructuring in the parameter list is cleaner than accessing by index inside.
- Prefer shallow destructuring. Deep nesting like
const [[a, [b, [c]]]] = datais hard to read. Extract one level at a time when nesting exceeds two levels.
Rune AI
Key Insights
- Position-based extraction: variables map to array indices in left-to-right order
- Default values replace only undefined: null, 0, false, and "" are valid and will not trigger defaults
- Rest pattern collects remaining:
const [first, ...rest]gathers all elements after the first - Variable swap in one line:
[a, b] = [b, a]eliminates the need for a temporary variable - Works with any iterable: strings, Sets, Maps, and generator results all support destructuring
Frequently Asked Questions
What is the difference between array and object destructuring?
Can I rename variables during array destructuring?
Does destructuring create a copy of the array?
What happens if I destructure an empty array?
Can I use destructuring with async/await?
Conclusion
Array destructuring transforms index-based access into clean, named variable extraction. It works with any assignment context (declarations, parameters, loops) and any iterable (arrays, strings, Sets, Maps). The core patterns to internalize are basic extraction (const [a, b] = arr), rest collection (const [head, ...tail] = arr), default values (const [x = 0] = arr), and the variable swap ([a, b] = [b, a]). Combined with map() and forEach() callback parameters, destructuring makes array processing in JavaScript significantly more readable.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.