Spread Operator (...)

JavaScript Spread Operator ... is used to allows iterables (string, array) to expand where zero or more arguments or elements (array) are required. Spread Operator turns elements of an array into arguments of function. spread operator is also used in Objects to copy another object data into new object being constructed.

In Arrays, spread expands array into elements.

Spread syntax can be used in

  1. Function Arguments
  2. Arrays
  3. Objects

Spread Operator Example


    function add(x,y){return x+y}
    let nums=[1,2];
    console.log( add(...nums) );

Spread in function arguments

Spread in function arguments can be used to spread arrays data into arguments. It converts an array elements into arguments of function called.

Sum Array elements using spread


    function add(x,y,z){ return x+y+z};
    let data=[1,2,3];

Check maximum value i array


    let data=[1,2,3];

Check minimum value i array


    let data=[1,2,3];

earlier apply method was used to achieve same results.

Math.max.apply(null,[1,2,3]) returns 3

Math.min.apply(null,[1,2,3]) returns 1

Spread Operator in Arrays

Spread Operator is also used in an array. It cab be used in push method, concat method etc. Here are some examples of spread operator in arrays.

push array into array

['a1', 'a2', 'a3', 'a4']

    let a1=['a','b'];
    let a2=['c','d'];

contact arrays

['a', 'b', 'c', 'd']

    let a1=['a','b'];
    let a2=['c','d'];
    let a3=a1.concat(...a2);

split string arrays

['a', 'b', 'c', 'd']

    let str="abcd";
    let arr=[...str];

Spread Operator in Objects

Spread Operator can also be used in objects. For example, to bind an object properties and values into another object.

Spread in object

{name: 'john', id:111, city: 'delhi', pin: 110001}

   let address={city:"delhi", pin:110001};
   let user={name:"john",id:111, ...address};