Rest, Spread and Destructuring in JavaScript
Tejaswini
Posted on October 19, 2020
- In java script rest , spread and destructuring are introduced to reduce the number of lines of code which are very useful for developers to minimize number of lines of code.
Rest
- Rest combines all the given numbers or anything into an array.
- For example,
If you want to find sum of 5 numbers
function sum1(...arr)
{
let sum=0;
for(let i=0;i<arr.length;i++)
sum=sum+arr[i];
return sum;
}
console.log(sum1(1,2,3,4,5));
Another Example
Given array of numbers sort the array
const arr1=(...arr)=>{
let i,j;
for(i=0;i<arr.length;i++)
{
for(j=0;j<arr.length-i;j++)
{
if(arr[j]>arr[j+1])
{
let temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
return arr;
}
console.log(arr1(3,2,4,1,5));
Spread
- Spread can be used to split multiple elements that are combined
let day1 = [ "1", "2" ];
let day2 = [ "3", "4" ];
let combined = [ "0", ...day1, ...day2 ];
let combined1 = ["0",day1,day2];
console.log (combined);
console.log(combined1);
Output
[0,1,2,3,4]
[0,[1,2],[3,4]]
To find maximum of given numbers
let findMax=(...arr)=>
{
arr.sort;
return arr[arr.length-1];
}
console.log(findMax(1,2,3,4));
Destructuring
It is used to reduce the code by dividing the arguments of a structure
var student={
name:'xyz',
subject:'ec',
cgpa:'10',
}
let res=(student)=>
{
let{name,subject,cgpa}=student; //Here we are directly assigning to split
return `Hi this is ${name},from ${subject} branch with cgpa of ${cgpa}`;
}
console.log(res(student));
- Without destructuring
let res=(student)=>
{
name=student.name;
subject=student.subject;
cgpa=student.cgpa;
//Here more lines of code
return `Hi this is ${name},from ${subject} branch with cgpa of ${cgpa}`;
}
console.log(res(student));
- Destructuring in function argument
function greetings ({ name, subject,cgpa}) {
return `Hi, I am ${name}.
from ${subject} branch
with cg of ${cgpa}`;
}
console.log(greetings(studentDetails));
Source where I learned: link
💖 💪 🙅 🚩
Tejaswini
Posted on October 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.