Use of spread operator in javascript

The spread operator is denoted by (...). It is used to spread out array elements from the array. It also allows an iterable(string and array) to be expanded in function calls, where zero or more arguments are expected. The spread syntax enumerates an object's properties and adds key-value pairs to being created object.

Difference between spread operator and rest operator

It is the same as the rest operator in the symbol, but it expands the elements from the array and the rest operator collects elements and shrinks them into elements of an array.

Syntax

There are three separate places, where the spread operator is applied.

  1. Function arguments list

    myFunction(a, b, ...iterableobject, c)

    { //function body }

  2. Array literals

    [ 1, a, ...iterableobject, '3']

  3. Object literals

    {...objectname, key:'value'}

Note:

An iterable object means an array or string, list, tuple etc. An object cannot be inserted in the function arguments list and array.

But an array can be inserted in an object.

Examples

Spread operator in function arguments

Let's use elements of an array in the function argument. Here is a function of the first, second and third winners in a game.

spread operator in array literals

Let's copy array elements to another array with the spread operator.

spread operator in object literals

Let's merge two objects into a single object.

Did you find this article valuable?

Support WebIndia by becoming a sponsor. Any amount is appreciated!