What is the difference between the spread operator and the rest operator? Both use `...`.
Show answer — try answering out loud first
Although both use ..., they do the opposite. Spread "expands" an array or object into individual elements. Rest "gathers" several elements into a single array. Spread is used when building; rest, when receiving.
- Spread (
...): takes an array or object and expands it. Useful for copying, combining arrays/objects, or passing elements as arguments. - Rest (
...): collects the remaining elements into an array. It's used in function parameters (to accept a variable number of arguments) or when destructuring.
A trick to remember them: if the ... is where something is created or called, it's spread (it expands). If it's where something is received or declared, it's rest (it gathers).
// SPREAD: expands arrays
const a = [1, 2];
const b = [3, 4];
const combinado = [...a, ...b];
console.log(combinado); // [1, 2, 3, 4]
// SPREAD: copies an array (shallow copy)
const copia = [...a];
console.log(copia); // [1, 2]
// SPREAD: expands objects
const base = { x: 1 };
const extendido = { ...base, y: 2 };
console.log(extendido); // { x: 1, y: 2 }
// SPREAD: pass elements as arguments
console.log(Math.max(...[5, 10, 3])); // 10
// REST: gathers arguments into an array
function sumarTodos(...numeros) {
return numeros.reduce((acc, n) => acc + n, 0);
}
console.log(sumarTodos(1, 2, 3, 4)); // 10
// REST: in destructuring
const [primero, ...resto] = [1, 2, 3, 4];
console.log(primero); // 1
console.log(resto); // [2, 3, 4]
- Confusing when it's spread and when it's rest. Remember: rest can only go at the end of the parameters (
function f(a, ...resto)), never in the middle. - Thinking that spread makes a deep copy. It's a shallow copy: nested objects still share their reference.
"Both use three dots, but they do the opposite. Spread expands an array or object into its elements, and I use it to copy, combine, or pass arguments. Rest does the reverse: it gathers several elements into an array, and I use it in function parameters to accept a variable number of arguments, or in destructuring to take the rest. The rule I use: if I'm creating or calling, it's spread; if I'm receiving, it's rest."
Write a function maximo(...nums) that returns the largest of all the numbers it receives.
See answer
function maximo(...nums) {
return Math.max(...nums);
}
console.log(maximo(3, 7, 2, 9, 1)); // 9