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']
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;
}
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"
As mentioned, we can also copy iterable elements from an array (or string).
const moreLetters = [...letters];
console.log(moreLetters);
// => logs ['c', 'a', 't']
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']
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" }
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 }
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
Top comments (0)