Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spread Syntax vs Rest Parameter in ES2015 / ES6

I am confused about the spread syntax and rest parameter in ES2015. Can anybody explain the difference between them with proper examples?

like image 686
Nur Rony Avatar asked Nov 24 '15 16:11

Nur Rony


People also ask

What is the difference between rest parameter and spread operator?

Rest Parameter collects all remaining elements into an array. Spread Operator expands collected elements such as arrays into single elements. The spread syntax only does a shallow copy one level deep. Only the last parameter can be a rest parameter.

What are the benefits of using spread syntax and how is it different from rest syntax?

Spread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite of rest syntax. Spread syntax "expands" an array into its elements, while rest syntax collects multiple elements and "condenses" them into a single element.

Is spread syntax ES6?

The spread syntax was introduced in the ES6 specification of JavaScript. It since has proved to be a valuable piece of code making the code clean and easy to understand.

What is rest parameter in ES6?

The rest parameter syntax allows us to represent an indefinite number of arguments as an array. With the help of a rest parameter a function can be called with any number of arguments, no matter how it was defined. Rest parameter is added in ES2015 or ES6 which improved the ability to handle parameter.


2 Answers

When using spread, you are expanding a single variable into more:

var abc = ['a', 'b', 'c'];  var def = ['d', 'e', 'f'];  var alpha = [ ...abc, ...def ];  console.log(alpha)// alpha == ['a', 'b', 'c', 'd', 'e', 'f'];

When using rest arguments, you are collapsing all remaining arguments of a function into one array:

function sum( first, ...others ) {      for ( var i = 0; i < others.length; i++ )          first += others[i];      return first;  }  console.log(sum(1,2,3,4))// sum(1, 2, 3, 4) == 10;
like image 184
TbWill4321 Avatar answered Sep 19 '22 21:09

TbWill4321


ES6 has new feature three dots ...

Here is how we can use these dots:

  1. As Rest/Collector/Gather
var [c, ...m] = [1,2,3,4,5]; // m -> [2,3,4,5] 

Here ...m is a collector, it collects the rest of the parameters. Internally when we write:

var [c, ...m] = [1,2,3,4,5]; JavaScript does following

var c = 1,     m = [2, 3, 4, 5]; 
  1. As Spread
var params = [ "hello", true, 7 ]; var other = [ 1, 2, ...params ]; // other => [1,2,"hello", true, 7] 

Here, ...params spreads so as to adding all of its elements to other

Internally JavaScript does following

var other = [1, 2].concat(params); 

Hope this helps.

like image 39
Manishz90 Avatar answered Sep 19 '22 21:09

Manishz90