Unpack an Array Into Variables
JavaScript Array Destructuring
Pull values out of an array and into named variables in one line — with defaults, skipping, and rest.
What you'll learn
- Destructure arrays into named variables
- Provide default values
- Use rest to capture the remainder
- Swap two variables in one line
Destructuring lets you pull values out of an array (or object) and into named variables — all in one expression.
The Basics
const colors = ["red", "green", "blue"];
const [a, b, c] = colors;
console.log(a, b, c); // "red" "green" "blue" Compare with the verbose version:
// Verbose:
const a = colors[0];
const b = colors[1];
const c = colors[2];
// Destructured:
const [a, b, c] = colors; Same effect, one line.
Skipping Items
Leave a slot blank with a comma:
const [a, , c] = ["red", "green", "blue"];
console.log(a); // "red"
console.log(c); // "blue" Defaults
If the array doesn’t have a value at that position, you can supply a default.
const [a = "x", b = "y", c = "z"] = ["red", "green"];
console.log(a); // "red"
console.log(b); // "green"
console.log(c); // "z" ← default The default only kicks in when the slot is undefined. null doesn’t
trigger it.
Rest — Capture the Rest
... at the end captures whatever’s left into an array.
const [first, second, ...others] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(others); // [3, 4, 5] Swapping Two Variables
The cleanest swap you’ll ever write.
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // 2 1 Destructuring Function Return Values
A function that returns an array becomes much nicer to call.
function minMax(numbers) {
return [Math.min(...numbers), Math.max(...numbers)];
}
const [lo, hi] = minMax([5, 1, 9, 3, 7]);
console.log(lo); // 1
console.log(hi); // 9 This pattern is everywhere in React (const [count, setCount] = useState(0))
and other modern libraries.
Destructuring Function Parameters
You can destructure right in the parameter list:
function greet([first, last]) {
console.log(`Hello, ${first} ${last}!`);
}
greet(["Ada", "Lovelace"]); // "Hello, Ada Lovelace!" Try It Yourself
Exercise
Swap two values
let x = 1;
let y = 2;
// swap them in one line
💡 Show hint
✅ Show solution
let x = 1;
let y = 2;
[x, y] = [y, x];
console.log(x, y);
Up Next
Last lesson of this chapter: sorting.
JavaScript Array Sort →