JavaScript › Destructuring, Spread & Rest
How does the rest parameter differ from the spread operator, even though they use the same '...' syntax?
IntermediateAnswer
Rest COLLECTS multiple arguments/elements INTO an array (used in function parameters or destructuring patterns); spread EXPANDS an array/iterable OUT into individual elements (used in calls or array/object literals). They're opposite operations sharing identical syntax.
function sum(...nums) { // rest: collects args into an array
return nums.reduce((a, b) => a + b, 0);
}
sum(...[1, 2, 3]); // spread: expands array into args -> 6Real-world example Rest to accept a variable number of arguments in a logging function; spread to pass an array of arguments to Math.max().