Spread
The spread operator was introduced with ES6, and is represented by an ellipse ( ... ). Spread allows for multiple items to be into an array or a function. We will cover the array portion in more depth later, so for now we'll focus on the function uses
spread syntax
Essentially, the spread operator allows us to place multiple items in a single variable, then insert them directly into the function as parameters. Complex functions can have many parameters, and as the code grows, being able to place those parameters in a variable rather than type them out each time is useful in cutting down on extra code. For example, consider the function for creating a Date object with a specific date and time:
new Date(year, month [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
This function can contain up to a total of 7 parameters. Imagine having to use that function over and over and over, writting it every single time. Using the spread operator, we can put all the parameters into an array and inject it straight into the function:
In the event that we need to create this Date object multiple times, using ...params
will significantly cut down on extra code and refactoring time. Later you'll learn other uses of the spread operator, including the ability inject items directly into a specific index of an array.
Last updated