➡️ In this article we will differentiate between the spread
& rest
operator of JS ❓
✍️ To start first, let's understand what is spread
& rest
one by one. So, it'll be easier for us to understand it in the big picture 🖼️ .
◼️ Spread operator (⚫ ⚫ ⚫)
- It starts with three dots and as the name itself suggests it's used to iterate
(spread)
over the elements of an array or objects.
To understand spread
working functionality it's important to understand its use cases
.
◻️ Use Cases
1. To concatenate
const company = ['tcs','wipro','infy'];
const ranking = [1,2,3];
const mySpread = [...company,...ranking];
console.log(mySpread);
// [ 'tcs', 'wipro', 'infy', 1, 2, 3 ]
The above example gives us the idea of merging two or more than two arrays with the help of the
spread
operator.But the same we can also achieve with the help of
concat
method like below.
const company = ['tcs','wipro','infy'];
const ranking = [1,2,3];
const myConcatenate = company.concat(ranking);
console.log(myConcatenate);
// [ 'tcs', 'wipro', 'infy', 1, 2, 3 ]
- The above code will also give us the same output.
🖋️ NOTE: In the case of concatenation
spread
may take more time to resolve based on the complexity of the large data set. Therefore, it's notrecommended
to usespread
in the above scenario.
2. To copy
Copying without spread operator
const company = ['tcs','wipro','infy'];
const myCompnay = company;
console.log(myCompnay);
// [ 'tcs', 'wipro', 'infy' ]
- The above code works fine but the problem arises when we modify the copied array but it impacts the original array as well which we didn't intend to.
let newElement = myCompnay.push("ibm");
console.log(myCompnay);
console.log(company);
// [ 'tcs', 'wipro', 'infy', 'ibm' ]
// [ 'tcs', 'wipro', 'infy', 'ibm' ] - > affected the original array.
Using the spread
operator to copy the array
const company = ['tcs','wipro','infy'];
const myCompnay = [...company];
console.log(myCompnay);
// [ 'tcs', 'wipro', 'infy' ]
let newElement = myCompnay.push("ibm");
console.log(myCompnay);
console.log(company);
// [ 'tcs', 'wipro', 'infy', 'ibm' ]
// [ 'tcs', 'wipro', 'infy' ] - > does not affect the original array.
3. To Math
JS does provide us the
Math
function to find min, max, etc from a list of numbers.But in case of
array
Math function doesn't work & will return aNaN
let arr = [1,2,3,-1];
console.log(Math.min(arr));
//NaN
In order to avoid it, we use spread
since it iterates over elements of arrays.
// with spread
let arr = [1,2,3,-1];
console.log(Math.min(...arr));
//-1
4. Strings to Array
We can iterate over the given string and expand it after converting it into an array.
Let's understand the above-said statement through an example.
let name = "VIRAT";
let myArr = [...name];
console.log(name);
// [ 'V', 'I', 'R', 'A', 'T' ]
◼️ Spread operator with Objects
1. Cloning an object
- We can use the spread operator to clone any object properties.
const circle = {
radius: 10
};
const clonedCircle = {...circle};
console.log(clonedCircle);
// { radius: 10 }
🖋️ NOTE: Cloning always creates a shallow copy.
2. Merging an object
- Like an array, we can also merge an object using the
spread
operator.
const circle = {
radius : 20
}
const style = {
backgroundColor : 'black'
}
const myCirle = {
...circle,
...style
}
console.log(myCirle);
// { radius: 20, backgroundColor: 'black' }
Now, we are quite well versed with the spread operator 💪 let's have a look into the rest operator ✍️
◼️ Rest Operator
As the name suggests itself
rest
is used to condense or compress the elements.It's very handy when we need to pass the
n
number of arguments to a function and we are not sure about their number, therest parameter
makes it really easier to do the task.
SYNTAX
function function_name(...arguments) {
statements;
}
- Let's understand the
rest operator
with an example.
1. Pass n
number of arguments to a function and return the sum of it.
function mySum(...args){
sum = 0;
for(let arg of args)
{
sum= sum + arg;
}
return sum;
}
console.log(mySum(1,2,3,4,5,6));
// 21
2. Passing rest parameters
as an argument while calling the function.
function cricket(bowler1, bowler2,...batter){
console.log(bowler1,bowler2);
console.log(batter);
}
cricket("Bumrah", "Anderson", "Virat", "Williamson", "Root", "Dhoni");
// Bumrah Anderson
// [ 'Virat', 'Williamson', 'Root', 'Dhoni' ]
3. Sorting the number passed in the argument by the user at the time of function invocation.
function num(...sortNum){
const mySort= sortNum.sort();
console.log(mySort);
}
num(1,4,7,9,0);
// [ 0, 1, 4, 7, 9 ]
Now, we are well aware of the rest
& spread
operators it's really easy to differentiate between these two.
🧠 In a nutshell: ...spread
is used to expand iterables into individual elements. Whereas ...rest
is used to condense the value into a JS array.
Before I sign out 🖐️
Thanks a ton
to read this article. It took plenty of time for me to first make a proper understanding of these methods and then simplify it in simple words which may save you time.
I hope this article comes in very handy for your day-to-day development & learning process.
Definitely would give you a better understanding of JS array methods.