HomeToolsAbout a20k

Spread and Rest

Spread vs Rest

Spread and Rest look identical (...)

Spread is the opposite of Rest syntax.

  • Spread expands an array into its elements
  • Rest collects multiple elements and condenses them into a single element

What is Spread

Allows an iterable (such as array or string) to be expanded in places where zero or more arguments or elements are expected.

function sum(x, y, z) { return x + y + z; } const numbers = [1, 2, 3]; console.log(sum(...numbers)); // 6

Spread on existing elements

In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.

Essentially making an update to an object with the new entries while preserving the existing elements

const colors = ['red', 'green', 'blue']; const newColors = [...colors, 'yellow']; console.log(newColors); // ['red', 'green', 'blue', 'yellow']

Common Use Cases

// function arguments function myFunction(a, ...iterableObj, b) // array literals [ 1, ...iterableObj, '4', 'five' ]; // object literals { key1: 'value1', ...obj, key2: 'value2' }

Primitives

Primitives can be spread in objects, but only string has enumerable own properties, and spreading anything else doesn't create properties on the new object.

const obj = { ...true, ..."test", ...10 }; console.log(obj); // { '0': 't', '1': 'e', '2': 's', '3': 't' }

Since true and 10 are primitive values without enumerable properties, spread ignores them.

Limitation

Spreading as a function's argument is limited to 65536 arguments (based on JSCore engine hard-coded limit)

What are Rest Parameters

Rest parameter allows a function to accept indefinite number of arguments as an array.

// rest parameter of arbitrary args function sum(...args) { ... } // rest parameter with prefixed parameters function someFunction(a, b, ...theArgs) { ... }
function someFunction(a, b, ...theArgs) { ... } someFunction("one", "two", "three", "four", "five"); // a, "one" // b, "two" // theArgs, ["three", "four", "five"]

Rules

  • Function definition can only have one rest parameter
  • Rest parameter must be the last parameter in the function definition
© VincentVanKoh