JavaScript Spread Operator

The spread operator is a new addition to the features available in the JavaScript ES6 version.


Spread Operator

The spread operator ... is used to expand or spread an iterable or an array. For example,

In this case, the code:

console.log(...arrValue)

is equivalent to:

console.log('My', 'name', 'is', 'Jack');

Copy Array Using Spread Operator

You can also use the spread syntax ... to copy the items into a single array. For example,


Clone Array Using Spread Operator

In JavaScript, objects are assigned by reference and not by values. For example,

Here, both variables arr1 and arr2 are referring to the same array. Hence the change in one variable results in the change in both variables.

However, if you want to copy arrays so that they do not refer to the same array, you can use the spread operator. This way, the change in one array is not reflected in the other. For example,


Spread Operator with Object

You can also use the spread operator with object literals. For example,

Here, both obj1 and obj2 properties are added to obj3 using the spread operator.


Rest Parameter

When the spread operator is used as a parameter, it is known as the rest parameter.

You can also accept multiple arguments in a function call using the rest parameter. For example,

Here,

  • When a single argument is passed to the func() function, the rest parameter takes only one parameter.
  • When three arguments are passed, the rest parameter takes all three parameters.

Note: Using the rest parameter will pass the arguments as array elements.

You can also pass multiple arguments to a function using the spread operator. For example,

If you pass multiple arguments using the spread operator, the function takes the required arguments and ignores the rest.


Note: Spread operator was introduced in ES6. Some browsers may not support the use of spread syntax. Visit JavaScript Spread Operator support to learn more.