Lesson 18 of 34 · Arrays
JavaScript Spread Operator and Array Destructuring
Three dots, ..., are one of the most useful pieces of syntax in modern JavaScript. Depending on where you put them, they either spread an array out into individual values or gather individual values into an array.
Combined with destructuring, which unpacks values from an array into variables, they make array code shorter, clearer and safer.
Spread: unpacking an array
Spread syntax expands an array's items in place. Inside an array literal, it's the easiest way to copy or combine arrays:
const warriors = ["Conan", "Xena"];
const mages = ["Merlin"];
const party = [...warriors, ...mages];
console.log(party); // [ 'Conan', 'Xena', 'Merlin' ]
const copy = [...warriors];
const withHealer = [...warriors, "Mercy"]; // add an item without mutating
console.log(warriors); // [ 'Conan', 'Xena' ] (unchanged)
Spread also turns an array into separate function arguments:
const rolls = [4, 17, 9];
console.log(Math.max(rolls)); // NaN (Math.max doesn't accept an array)
console.log(Math.max(...rolls)); // 17, same as Math.max(4, 17, 9)
And it works on any iterable, such as a string: [..."orc"] is [ 'o', 'r', 'c' ].
A spread copy is shallow: the new array is separate, but if it contains objects or nested arrays, both arrays point to the same inner values.
Rest parameters: gathering arguments
The same three dots in a function's parameter list do the opposite: they gather all remaining arguments into a real array:
function logAll(label, ...messages) {
for (const message of messages) {
console.log(`[${label}] ${message}`);
}
}
logAll("quest", "Find the key", "Open the door");
// [quest] Find the key
// [quest] Open the door
The rest parameter must come last, and it's always an array, even if it's empty.
Array destructuring
Destructuring lets you pull items out of an array and into variables in one line, based on position:
const podium = ["Ada", "Linus", "Grace", "Alan"];
const [gold, silver, bronze] = podium;
console.log(gold, silver, bronze); // Ada Linus Grace
You can skip items with empty slots, provide default values, and collect the rest:
const [, second] = podium; // skip the first item
const [winner, ...others] = podium; // others is [ 'Linus', 'Grace', 'Alan' ]
const [a, b, c, d, e = "nobody"] = podium; // e falls back to its default
Swapping and returning several values
Destructuring makes swapping two variables a one-liner:
let left = "sword";
let right = "shield";
[left, right] = [right, left];
console.log(left, right); // shield sword
It also lets a function effectively return several values. Return an array and destructure it at the call site:
function minAndMax(numbers) {
return [Math.min(...numbers), Math.max(...numbers)];
}
const [lowest, highest] = minAndMax([8, 3, 11]);
console.log(lowest, highest); // 3 11
Common mistakes
- Passing an array where separate values are expected.
Math.max(arr)givesNaN; spread it:Math.max(...arr). - Putting the rest element anywhere but last.
const [...rest, last] = arris aSyntaxError. - Assuming spread is a deep copy. Nested objects and arrays are still shared between the copy and the original.
- Spreading an empty array into
Math.max.Math.max(...[])is-Infinity, andMath.min(...[])isInfinity.
Assignment
Write four functions:
mergeParties(partyA, partyB)returns a new array with all members ofpartyAfollowed by all members ofpartyB. The input arrays must not change.mergeParties(["Ada"], ["Linus", "Grace"])→["Ada", "Linus", "Grace"]
minMax(numbers)returns a two-item array[smallest, largest]. You can assume the array isn't empty.minMax([4, 9, 1, 7])→[1, 9]
sumAll(...numbers)takes any number of arguments (use a rest parameter) and returns their sum. With no arguments it returns0.sumAll(1, 2, 3, 4)→10
swapFirstTwo(items)returns a new array where the first two items have swapped places and everything else stays the same. Use destructuring.swapFirstTwo(["a", "b", "c", "d"])→["b", "a", "c", "d"]
Premium lesson
Unlock the full Learn JavaScript course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Destructuring and multiple values in other languages
Need a quick reminder? The JavaScript cheat sheet has every topic of Learn JavaScript on one page.
Lesson last updated on .