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.

JavaScriptbeginner
14 min read

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

javascriptjavascript
// 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.0060

The variable names on the left map to array positions on the right, in order.

Basic Syntax

javascriptjavascript
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 anything

Destructuring works with let and var as well:

javascriptjavascript
let [x, y] = [10, 20];
x = 30; // Reassignable with let
 
const [a, b] = [10, 20];
// a = 30; // TypeError with const

Skipping Elements

Leave gaps in the destructuring pattern to skip positions:

javascriptjavascript
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); // 0

Default Values

When the array has fewer elements than the pattern, missing positions default to undefined. You can assign fallback values:

javascriptjavascript
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:

javascriptjavascript
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

javascriptjavascript
const items = ["first", "second", "third", "fourth"];
 
const [head, ...tail] = items;
console.log(head); // "first"
console.log(tail); // ["second", "third", "fourth"]

Rest with Empty Remaining

javascriptjavascript
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:

javascriptjavascript
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); // 1

This works with any number of variables:

javascriptjavascript
let x = 1, y = 2, z = 3;
 
[x, y, z] = [z, x, y];
console.log(x, y, z); // 3 1 2

Nested Destructuring

Destructure arrays inside arrays by nesting the pattern:

javascriptjavascript
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 6

Partial Nested Extraction

javascriptjavascript
const data = [1, [2, 3, 4], 5];
 
const [first, [, middle], last] = data;
console.log(first);  // 1
console.log(middle); // 3
console.log(last);   // 5

Deep Nesting

javascriptjavascript
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:

javascriptjavascript
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); // 88

Ignoring Return Values

javascriptjavascript
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); // 4523

Destructuring in Function Parameters

Accept array arguments and destructure them directly in the parameter list:

javascriptjavascript
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

javascriptjavascript
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:

javascriptjavascript
// 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:

javascriptjavascript
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:

javascriptjavascript
// 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:

javascriptjavascript
// 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:

javascriptjavascript
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 2

Missing parentheses in assignment destructuring:

javascriptjavascript
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 2

Over-destructuring:

javascriptjavascript
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); // 0

Best Practices

  1. Use meaningful variable names. const [lat, lng] = coords is far clearer than const [a, b] = coords.
  2. Provide defaults for optional positions. When the array might have fewer elements than expected, set defaults to avoid undefined.
  3. Use rest for variable-length arrays. const [head, ...tail] is the standard pattern for processing the first element differently.
  4. Destructure in function parameters. When a function receives an array, destructuring in the parameter list is cleaner than accessing by index inside.
  5. Prefer shallow destructuring. Deep nesting like const [[a, [b, [c]]]] = data is hard to read. Extract one level at a time when nesting exceeds two levels.
Rune AI

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
RunePowered by Rune AI

Frequently Asked Questions

What is the difference between array and object destructuring?

rray destructuring uses square brackets `[a, b]` and matches by position (index 0, 1, 2...). Object destructuring uses curly braces `{a, b}` and matches by property name. Arrays are positional, objects are named.

Can I rename variables during array destructuring?

Not directly. Array destructuring assigns to the variable names you write. If you need a different name, assign to one variable and then use `const newName = oldName`. Object destructuring supports renaming with the colon syntax (`{ old: newName }`), but arrays do not have this feature.

Does destructuring create a copy of the array?

No. Destructuring extracts values from the array but does not copy the array itself. If an extracted value is an object or array (reference type), the variable holds a reference to the same object. Modifying it will affect the original data.

What happens if I destructure an empty array?

ll variables receive `undefined` unless defaults are provided. The rest element receives an empty array `[]`. No error is thrown.

Can I use destructuring with async/await?

Yes. Destructure the resolved value: `const [data, error] = await someAsyncFunction()`. This is a common pattern for functions that return [result, error] tuples instead of throwing exceptions.

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.