spread operator in js

3 Min. Read
Sep 16, 2019

Spread Operator in Javascript

Spread Operator is a pretty nifty feature that was baked into ES6. The spread operator is ‘…’. It allows expression to be expanded in places where multiple elements are expected to feature. Spread syntax can be used to operate on arguments, elements or object expressions.

Some of the uses of spread operator

  • Add elements of existing array into a new array.
1
2
3
  var dogNames = ['Max', 'Harley', 'Tom'];
  var names = ['Ram',...dogNames, 'Hari', 'Shyam'];
  console.log(names); //['Ram', 'Max', 'Harley', 'Tom', 'Hari', 'Shyam']
  • Pass elements of an array as arguments to a function
1
2
3
4
5
   function addThreeNumbers(x,y,z) {
    console.log(x+y+z);
    }
    var args = [1,2,3];
    addThreeNumbers((args);
  • Copy Array
1
2
3
4
  var arr = [1,2,3];
  var arr2 = [...arr];
  var arr3 = arr; //they reference to the same array in memory (undesired, as changes to one are reflected in another)
  console.log(arr2); //[1,2,3]
  • Concatenate array literals
1
2
3
4
  var arr = [1,2,3];
  var arr2 = [4,5,6];
  console.log([arr1, arr2]); [[1,2,3], [4,5,6]] //escape nested array
  console.log([...arr1, ...arr2]); //escape nested array
  • Iterate through individual items of an array
1
2
3
  var arr = [1,2,3];
  console.log(arr); //[1,2,3]
  console.log(...arr); //1 2 3

This is particularly useful in functions that have to act on individual items from strings, sets, or arrays.

1
2
3
4
5
   Math.min(..."9832"); //2

   const nums = new Set([1, 2, 3, 4, 5]);
   Math.max(...nums); //5

  • Pass variable number of arguments to a function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  function foo (...args) {
    console.log(args);
   }

   foo('ram', 'hari'); //['ram', 'hari']
   foo(1,2,3,4,5); //[1,2,3,4,5]
   foo([55,22], [77,66]); //[[55,22], [77,66]]

  function foo(x, ...args) {
    console.log(x, args, ...args, arguments);
   }

  foo('a', 'b', 'c', z='d');
    //a
    //Array(3) [ "b", "c", "d" ]
    //b c d
    //Arguments
       // 0: "a"
        //​1: "b"
        //2: "c"
        //3: "d"
        //length: 4
  • For Object Literals (New from ES2018)
1
2
  var car = {type:"Fiat", model:"500", color:"white"};
  var newCar = {...car};