3 dots ... in JavaScript

ECMAScript 6 was the second major revision to JavaScript.

ECMAScript 6 is also known as ES6 and ECMAScript 2015; ... is one of these new Javascript functionalities.This is one of the cool new feature of Javascript's ECMA6.

The three dots in JavaScript are spread / rest operator.

  • Rest Parameters

With rest parameters, we can gather any number of arguments into a array. Rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments.

The array2 has the elements of array1 copied into it. Any changes made to array1 will not be reflected in array2 and vice versa.

If the simple assignment operator had been used then array2 would have been assigned a reference to array1 and the changes made in one array would reflect in the other array which in most cases is undesirable.



let array1 = ['h', 'e', 'l', 'l', 'o'];
let array2 = [...array1];
console.log(array2);


//output
//['h', 'e', 'l', 'l', 'o']
  • Spread Operators

The spread operator is used to expand elements of an iterable (like an array) into places where multiple elements can fit.


function myFunc(x, y, ...params) { // used rest operator here
  console.log(x);
  console.log(y);
  console.log(params);
}
var inputs = ['a', 'b', 'c', 'd', 'e', 'f'];
myFunc(...inputs); // used spread operator here
// 'a'=(x)
// 'b'=(y)
// ['c', 'd', 'e', 'f']=(params)



//output
//['a','b','c','d','e','f']

There have always been a variety of ways to combine arrays, but the spread operator gives use a new method for combining arrays:

let desserts = ['cake', 'cookie', 'donut'];
let desserts1 = ['icecream', 'flan', 'frozen yoghurt', ...desserts];
console.log(desserts1);

//Appending baked_desserts after flan
let desserts2 = ['icecream', 'flan', ...desserts, 'frozen yoghurt'];
console.log(desserts2);



// output
[ 'icecream','flan','frozen yoghurt','cake', 'cookie', 'donut' ]
[ 'icecream', 'flan', 'cake', 'cookie', 'donut', 'frozen yoghurt' ]

With spread operator, Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

var obj1 = { capital: 'Delhi', x: 62 };
var obj2 = { capital: 'Lucknow', y: 78 };

var clonedObj = { ...obj1 };
// Object { capital: "Delhi", x: 62 }

var mergedObj = { ...obj1, ...obj2 };
// Object { capital: "Lucknow", x: 62, y: 78 }

There's an easy way to distinguish between them: When three dots (…) is at the end of function parameters, it's "rest parameters" and gathers the rest of the list of arguments into an array. When three dots (…) occurs in a function call or alike, it's called a "spread operator" and expands an array into a list.