ππ©π«πππ ππ§π πππ¬π ππ©ππ«πππ¨π« 101π
Prerequisites: JavaScript ES6
JavaScript uses three dots (...) for both the rest and spread operators. But these two operators are not the same. It was introduced in ECMAScript 2015 and they allow us to write more concise and flexible code like most of the other ES6 features do.
πSpread
The spread operator allows us to expand the collected elements of an iterable data type like strings, arrays, or objects into individual elements in places. It helps to create a list of elements from a list by spreading out the values of an iterable where zero or more arguments (function calls) or elements (array literals) or key-value pairs (object literals) are expected.
Syntax: var var_name = [...iterable];
The use of the spread operator is explained below,
πFunction calls
The spread operator can be used to take elements of an array and pass them as a list of arguments into a function.
Let's jump to the example,
printAnimals =(Animal1, Animal2, Animal3)=>{
console.log(Animal1 + ',' + Animal2 + ',' +Animal3);
};
(Animal1, Animal2, Animal3)=>{
console.log(Animal1 + ',' + Animal2 + ',' +Animal3);
}
let animals = ['tiger', 'elephant', 'lion'];
printAnimals(...animals);
Output:
The function printAnimals
takes in three parameters and we want to pass three arguments stored in animal
array. When we call the function, the spread operator unpacks the passed array of arguments, βtigerβ, βelephantβ, and βlionβ.
πArray Literals
Although we have concat
and slice
method the spread operator provides us a new quick method for merging and copying arrays.
const arr1 = ['coffee','tea', 'milk']
const arr2 = ['juice', 'smoothie']
var beverages = arr1.concat(arr2); //without spread
var beverages = [...arr1,...arr2]; // with spread
console.log(beverages)
Output:
The above example shown, the spread operator is used to add the elements of the arr2
to the end of the arr1
. This process creates a new array non-destructively by concatenating two existing arrays.
const arr1 = ['coffee','tea', 'milk']
var arrCopy1 = arr1.slice() //without spread
var arrCopy2 = [...arr1] //with spread
console.log(arrCopy1);
console.log(arrCopy2);
Output:
The example above copies arr1
into arrCopy2
. The changes you will do on the arrCopy2
will not affect the arr1
, this process makes an exact copy of an existing array.
There are other use cases like,
Remove duplicate entries from Array
const arr1 = ['coffee','tea','milk','coffee','milk'];
const arr1Copy = [...new Set(arr1)];
console.log(arr1Copy)
Output:
Convert string to Array
const myBeverage = 'tea';
var bevArr = [...myBeverage]
console.log(bevArr)
Output:
Find min max
var max1 = Math.max(3,2,1,5,-10); // without spread
var mynums = [3,2,1,5,-10];
var max2 = Math.max(...mynums) // with spread
console.log(max2)
Output:
πObject Literals
Another use case of the spread operator is to use it in object literals. Since ES2018, it is possible to use the spread operator to copy and merge objects:
The spread operator only provides a shallow copy of its own enumerable properties from a provided object and then returns the result in a new object by excluding the prototype.
πRest Operator
The Rest operator is the opposite of Spread operator. While spread operator expands elements of an iterable, rest operator compresses them. It collects several elements. In functions when we require to pass arguments
but were not sure how many we have to pass, the rest parameter makes it easier.
Syntax:
function function_name(...arguments) {
statements;
}
The rest parameter, which is the same syntax as the spread operator, can be used for destructuring arrays and objects to unpack their data into different individual variables.
function log(a,...numbersToLog){
console.log(a);
console.log(numbersToLog);
}
log(1,2,3)
Output:
In the example above, the rest parameter collected the rest of the elements of log
into a new array. Note that the rest parameter can only be the last parameter.
The rest parameter can be very useful when we work with an indefinite number of parameters in the functions. See the following example:
add=(...numbers)=>{
let answer = 0;
for(let num of numbers){
answer+= num;
}
return answer;
}
add(1,23,4,5,6,7,8,9,4,5); //72
add(1,2,3) //6
The add()
function receives a rest parameter β¦numbers and adds the arguments we pass into it when it is called. This makes functions more flexible and helps us to run them with as many arguments as we want. The first function call add(1, 2, 3)
returns 6 and the second function call add(1,23,4,5,6,7,8,9,4,5)
with more arguments returns 72. As shown in this example, the rest parameter can gather any number of arguments into an array.
Remember that the arguments object is an array-like object but does not support array methods like map()
and forEach()
unless you convert it to a real array. Since the rest parameter gives us an array, those array methods can now be easily used.
πReferences
I hope you have like this blog. Happy codingπ
Always remember, no one reached to the top in one shot. It took them a lot more struggle and hard work than you can imagine. So strive for knowledge, and keep moving forward. Thank you