Spread Syntax

Spread Syntax

Spread syntax (...) comes from ES6 and it essentially lets you pull out the values and fields of any object, or array into something else.

For example when merging two objects you can use the spread syntax to pull all of the fields from one object into another. Or when using an array you can pull all of the array items into another array.

Another use would be in the arguments of a function.

If you want to get all arguments passed into a function as an array you can use the spread syntax to put all the arguments into an array that you name.

Lastly, as a working example, let's say you need a function that can accept many arrays of numbers as parameters and you expect it to find the sum of all the numbers across all arrays passed into it.

One way in which you could do this would be to find all the arrays passed in using spread syntax to give you an array of arrays with numbers and then combine all the arrays into a single array of numbers using a loop and spread syntax, where each iteration you would re-define the single array to be equal to the current items it has as well as the numbers from the current iteration's array.

After that you can loop over the single array of numbers adding each one and then returning the overall value.

Further resources

Related topics

© 2024 MWXYZ