Javascript Rest and Spread Operators
By Saket Bhatnagar••Beginner to Intermediate
rest and spread
Rest parameter
- 1Rest parameter is used to accept multiple values , stored them in an array and array's reference will stored the variable that we have used for rest.
- 2Rest can accept n number of values and stored them in an array.
- 3To make a variable rest , we have to put '...' before variable name.
- 4Syntax : let ...variable_name;
- 5We can use rest in function when we don't know the exact number arguments.
- 6In function , there can be only one rest parameter and it should be the last parameter.
- 7 1function details(a,b,...z) { console.log(a);2//103console.log(b);4//205console.log(z[0]);6//307console.log(z[1]);8//409console.log(z[2]);10//5011console.log(z[3]);12//6013console.log(z[4]);14//701516}17details(10,20,30,40,50,60,70);18//function call
Here , if we pass two values it will be stored in a,b respectively and further value will stored by rest in an array. We can pass n number of values.
- 8
Uses of REST parameter.
1. REST parameter can be used in function definition parameter list to accept multiple values.
2. It can also be used in array and object destructuring.
- 9
If we pass literals to three dots (...) , it will accept all literals and behave as a rest parameter.
Spread operator
- 1It is used to unpack elements from iterables (like array or object).
- 2
Use cases :
- The unpack data can be sent to the function as an argument by using spread operator in the function call statement.
1let arr = [10, 2, 3, 40, 500, 6];23function sum(...data) {4 let acc = 0;5 for (let val of data) {6 acc = acc + val;7 }8 return acc;9}10let result = sum(...arr);11console.log(result);1213Output: 5611415// ...data - rest parameter16// ...arr - spread operator- We can ask the spread operator to store the unpack element in array object by using spread operator inside [ ] brackets.
1let new_arr = [...arr];2console.log(new_arr);34Output: [10, 2, 3, 40, 500, 6];- We can ask the spread operator to store the unpack element in object by using spread operator inside { } brackets.
1let human1 = {2 name: "Chombu",3 age: 21,4};56let human2 = { ...human1 };78console.log(human2);910Output: { name: "Chombu", age: 21, }; - 3
If we do not pass literals to three dots (...) , it will unpack all literals and behave as a spread parameter.