Let's start off with a quick definition:
The spread operator is essentially a more compact way to apply multiple parameters to functions. The traditional route is the following:
function func1(param1, param2, param3, ..)
We are all pretty familiar with this syntax for the most part. If we need a parameter, we simply add it to the list. The spread operator changes things up a bit however and can instead let us do something like the following:
The parameters in this case will be added dynamically when we call the function with a given parameter list. Both the following examples would be valid in this case.
func1(1, 3, 4, 5);
func1(3, 4, 5, 6, 8, 9);
The spread operator can also be used surprisingly to combine multiple arrays into one.
let array1 = [1, 2, 3];
let array2 = [3, 4, 5];
let array3 = [...array1, ...array2];
While, the syntax seems cumbersome in this example, it is important to note that the traditional method of combining arrays is the following:
let array1 = [1, 3, 5, 5, 5];
let array2 = [3, 4, 5, 6];
let array3 = [3, 4, 5];
let array4 = array1.concat(array2, array3);
I always found this syntax to be unclear, mainly because it involves that you reference the first array that you are combining in order to call the built-in concat function. Whereas, with the spread operator, you simply just list the arrays that you want to combine preceded with 3 dots.
Applying function parameters
function func2(param1, param2, param3)
return param1 + param2 + param3;
The typical way of calling this function and passing in values would be the following:
func2(1, 2, 3);
An alternative method would be to use the spread operator.
let array1 = [2, 3, 4];
Again, not really too sure how this syntax is beneficial or an improvement over the traditional way of passing in arguments, but it is there as an option in case you find yourself needing it.
Hopefully this post gives you some more insight into the somewhat new and somewhat powerful capabilities of the spread operator in ES6. Start using it today and if you find out how the 3rd option is beneficial, please let me know as I would love to see some use cases.
Did you find this article helpful?
Walter G. is a software engineer, startup co-founder, former CTO of several tech companies and currently teaches programming for a coding bootcamp. He has been blogging for the past 5 years and is an avid BMX rider, bio-hacker
and performance enthusiast.