Spread Syntax

benlongcp - Aug 2 - - Dev Community

In JavaScript, spread syntax is a way to expand an indexed or iterable datatype into a iterable datatype, specifically an array or object.

Whereas rest syntax uses a similar structure to spread, rest parameters allow a function to be passed an unknown quantity of arguments. Spread syntax inverts this process such that an individual collection is protracted into its constituent elements.

This is particularly useful when an object or array needs to have its elements transferred to a new object or array. Additionally, in a function's arguments, the spread operator can be used to pass individual elements to the function's parameters.

For example, let's say we have an array of letters:

const letters = ['c', 'a', 't']
Enter fullscreen mode Exit fullscreen mode

And let's say we have a function that takes three elements and does something with them:

let spell = (x, y, z) => {
  return y + x + z;
}
Enter fullscreen mode Exit fullscreen mode

If we want to pass the individual elements from out letters array, we can use the spread operator when we call the function and it will automatically disperse the array elements into the arguments list:

console.log(spell(...letters));
// => logs "act"
Enter fullscreen mode Exit fullscreen mode

As mentioned, we can also copy iterable elements from an array (or string).

const moreLetters = [...letters];
console.log(moreLetters);
// => logs ['c', 'a', 't']
Enter fullscreen mode Exit fullscreen mode

This can also allow us to combine or concatenate arrays more easily:

const evenMoreLetters = [...letters, ...moreLetters];
console.log(evenMoreLetters);
// => logs ['c', 'a', 't', 'c', 'a', 't']
Enter fullscreen mode Exit fullscreen mode

The array can also be spread into an object, where the array element is the value, and the index number is the key:

const objLetters = {...letters}
console.log(objLetters);
// => logs { 0: "c", 1: "a", 2: "t" }
Enter fullscreen mode Exit fullscreen mode

Objects can also be merged using the spread syntax:

const objUno = {
  'one': 1
}

const objDeux = {
  'two': 2
}

const objDrei = {...objUno, ...objDeux};

console.log(objDrei);
// => logs { one: 1, two: 2 }
Enter fullscreen mode Exit fullscreen mode

While merely scratching the surface, this demonstrates the syntactical power of the spread operator in streamlining tasks such as copying and combining iterable datatypes, as well as passing multiple arguments to a function. As always, the less code we have to write, the easier our lives as developers will be.

Citations: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

.
Terabox Video Player