JavaScriptEasy
What is the rest operator?
Rest syntax (...name) collects the remaining items into a single array or object: extra function arguments into an array, leftover array elements, or leftover object properties.
Rest parameters
function sum(...numbers) gathers all arguments into a real array (unlike the old arguments object, which is array-like and does not exist in arrow functions). It must be the last parameter, and there can be only one.
Rest in destructuring
- Arrays:
const [first, ...others] = list. - Objects:
const { id, ...data } = recordis a clean way to remove a property without mutating the original.
Rest vs spread
They use the same ... but do opposite things:
- Rest appears where values are received (parameters, the left side of destructuring) and collects them.
- Spread appears where values are provided (calls, array/object literals) and expands them.
Practical patterns
- Variadic helpers:
log(level, ...messages). - Forwarding arguments:
(...args) => original(...args)in wrappers like debounce and memoize. - Omitting fields before sending data:
const { password, ...publicUser } = user. - Splitting props in React components:
function Button({ variant, ...rest }) { return <button {...rest} /> }.
Code example
js
1function sum(...numbers) {2 return numbers.reduce((total, n) => total + n, 0);3}4console.log(sum(1, 2, 3, 4)); // 105console.log(sum()); // 067function log(level, ...messages) {8 console.log(`[${level.toUpperCase()}]`, messages.join(" "));9}10log("info", "server", "started", "on", 3000); // [INFO] server started on 30001112const [winner, ...runnersUp] = ["Ada", "Grace", "Linus"];13console.log(winner, runnersUp); // Ada ["Grace", "Linus"]1415const record = { id: 7, name: "Ada", password: "hunter2" };16const { password, ...publicUser } = record;17console.log(publicUser); // { id: 7, name: "Ada" }1819// Forwarding arguments in a wrapper20function withTiming(fn) {21 return (...args) => {22 const start = performance.now();23 const result = fn(...args); // spread them back out24 console.log(`${fn.name} took ${(performance.now() - start).toFixed(2)}ms`);25 return result;26 };27}28console.log(withTiming(sum)(5, 5)); // 10
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.