AI Hints
Home›JavaScript Tutorial›Modern Array Tools
JavaScript · Lesson 53 of 138

Spread and Rest

Three little dots.

⏱ 2 min read▶ Video at 1:04:23🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Three little dots do two opposite jobs in JavaScript. Spread unpacks an array into separate values. Rest packs separate values into an array. Both are used all the time.

Spread and Rest
From the video: Spread and Rest
  • Three dots
  • Spread unpacks
  • Rest packs

Spreading and gathering

Spread copies the items of one array into a new one, so we can combine arrays, or add items, without changing the originals. Spreading into math dot max passes each number separately. And in a function's parameters, rest gathers any number of arguments into an array. Run it.

app.jsjavascript
const a = [1, 2];
const b = [3, 4];
const both = [...a, ...b, 5];
console.log(both);

console.log(Math.max(...both));

function sum(...nums) {
  return nums.reduce((t, n) => t + n, 0);
}
console.log(sum(1, 2, 3, 4));
Output
[ 1, 2, 3, 4, 5 ]
5
10

A quick copy

Spread is the easiest way to copy an array. Copy equals square brackets, dot dot dot, original. Changing the copy won't change the original. It's a shallow copy, which means arrays inside arrays are still shared. We'll talk about that more with objects.

keyvalue
[...arr]copy an array
[...a, ...b]combine arrays
fn(...arr)spread as arguments
function f(...args)rest gathers

Combining objects

Spread works on objects too. Here, default settings are combined with the user's choices. Later properties win, so the user's theme replaces the default. And rest in a function's parameters gathers any number of arguments into an array. Run it.

app.jsjavascript
const defaults = { theme: "light", fontSize: 16, sound: true };
const choices = { theme: "dark" };

const settings = { ...defaults, ...choices };
console.log(settings);

function total(...prices) {
  return prices.reduce((a, b) => a + b, 0);
}
console.log(total(2, 3), total(1, 2, 3, 4));
Output
{ theme: 'dark', fontSize: 16, sound: true }
5 10

Summary

Spread unpacks arrays into values, and rest gathers values into an array. Next, destructuring, unpacking arrays into variables.

Key takeaways
  • ...spread
  • ...rest
  • [...arr] copies
Next up: Destructuring Arrays — unpacking