DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Tejaswini
Tejaswini

Posted on

Rest, Spread and Destructuring in JavaScript

  • 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));
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode
  • 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));
Enter fullscreen mode Exit fullscreen mode
  • 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));
Enter fullscreen mode Exit fullscreen mode

Source where I learned: link

Top comments (0)

Why You Need to Study Javascript Fundamentals

>> Check out this classic DEV post <<