# Spread operator in JavaScript

ES6 introduced a special operator `...` called spread.

When the spread operator is placed in front of an array, it splits the array into individual values, turning the array into a set of parameters needed to call the function.

It probably sounds confusing, so let's look at a simple example. Let's say we have a function that takes `3` parameters and returns their sum:

`function func(num1, num2, num3) { return num1 + num2 + num3; }`

Let's also have an array of three elements:

`let arr = [1, 2, 3];`

Obviously, we cannot just take and pass this array as a function parameter, like this:

`let arr = [1, 2, 3]; func(arr);`

Indeed, in this case, the entire array will fall into the first parameter of the function, but a number must be passed to this parameter (and to other parameters too).

Of course, you can do the following:

`let arr = [1, 2, 3]; func(arr[0], arr[1], arr[2]);`

But there is an easier way - to use the spread operator:

`let arr = [1, 2, 3]; func(...arr);`

The presence of a variable is optional - you can apply spread directly to the array:

`func(...[1, 2, 3]);`

Given an array:

`let arr = [1, 2, 3, 4, 5];`

Also given is the function:

`function func(num1, num2, num3, num4, num5) { return num1 + num2 + num3 + num4 + num5; }`

Use the above function to find the sum of the array elements.

← →
↑
en ru