rest vs spread - jellyfish-tom/TIL GitHub Wiki

[SOURCES]

Rest operator

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

function f(a, b, ...theArgs) {
  // ...
}

A function's last parameter can be prefixed with ... which will cause all remaining (user supplied) arguments to be placed within "standard" javascript array. Only the last parameter can be a "rest parameter".

There are three main differences between rest parameters and the arguments object:

  • rest parameters are only the ones that haven't been given a separate name (i.e. formally defined in function expression), while the arguments object contains all arguments passed to the function;
  • the arguments object is not a real array, while rest parameters are Array instances, meaning methods like sort, map, forEach or pop can be applied on it directly;
  • the arguments object has additional functionality specific to itself (like the callee property).

Spread operator

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));

Rest vs Spread

Rest syntax looks exactly like spread syntax, but is used for destructuring arrays and objects. In a way, rest syntax is the opposite of spread syntax: spread 'expands' an array into its elements, while rest collects multiple elements and 'condenses' them into a single element.