SyntaxStudy
Sign Up
JavaScript Intermediate 7 min read

Array Destructuring

Array Destructuring

Destructuring assignment is a concise syntax for unpacking values from arrays (or properties from objects) into distinct variables. Array destructuring uses position — the first variable gets the first element, the second gets the second, and so on.

Basic Destructuring

Wrap the variable names in square brackets on the left side of an assignment. You can skip elements with commas and provide default values for missing elements.

Swapping Variables

Array destructuring enables a one-line variable swap without a temporary variable — a classic party trick that is also genuinely useful.

Rest in Destructuring

Use the rest syntax (...rest) as the last element on the left to collect all remaining array items into a new array.

Function Return Values

Functions can return arrays and callers can destructure the result, giving multiple return values a clean, named feel.

Example
const [first, second, third] = [10, 20, 30];
console.log(first, second, third); // 10 20 30
const [, , x] = [1, 2, 3];
console.log(x); // 3
const [a = 5, b = 7] = [1];
console.log(a, b); // 1  7
let p = 1, q = 2;
[p, q] = [q, p];
console.log(p, q); // 2  1
const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // 1
console.log(tail); // [2,3,4]
function minMax(arr) {
  return [Math.min(...arr), Math.max(...arr)];
}
const [min, max] = minMax([3, 1, 4, 1, 5]);
console.log(min, max); // 1  5
Pro Tip

Destructure function parameters directly when a function receives an array argument — it makes the code self-documenting and avoids magic index numbers inside the function body.