How to use rest and spread operators with functions
· Category: JavaScript
Short answer
Rest parameters (...args) gather remaining arguments into an array, while the spread operator (...arr) expands an array into individual arguments or elements.
Steps
- Use rest parameters in function definitions:
javascript function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0); } console.log(sum(1, 2, 3)); // 6 - Combine rest with named parameters:
javascript function log(level, ...messages) { console[level](...messages); } - Use spread to call functions with array elements:
javascript const nums = [10, 20, 30]; console.log(Math.max(...nums)); // 30 - Use spread to copy and merge arrays:
javascript const a = [1, 2]; const b = [3, 4]; const merged = [...a, ...b];
Tips
- Rest must be the last parameter in a function signature.
- Spread works on any iterable, including strings and NodeLists.
Common issues
- Confusing rest and spread syntax context; rest is in declarations, spread in calls/literals.
- Shallow copying with spread means nested objects still share references.