Rest & Spread

Rest & Spread

Destructuring in JS

Hola Coders!

In this article we will learn about spread and rest in JavaScript and to learn it, first we need to understand the concept of destructuring as well.

Destructuring

Let's learn how to pick the data. Destructuring can be achieved in arrays and objects. Need to remember whatever datatype in on right hand side, similar should be on left hand side then, probably we can destructure it.

Destructuring in Arrays

Following is the example which showcases how arrays are destructured.

const user = [5, "akshita", "monitor"]

let [rollNo, name, role] = user

console.log(rollNo) //5
console.log(name)   //akshita
console.log(role)   //monitor

Destructuring in Objects

Following is the example which showcases how objects are destructured.

const myUser = {
    rollNo: 4,
    name:"akshita",
    role: "admin"
}

const {rollNo, name, role} = myUser
console.log(rollNo) //5
console.log(name)   //akshita
console.log(role)   //monitor

NOTE: While destructuring objects variable names should be same as key as mentioned in the object.

Spread and Rest Operator

Amazing thing about spread and rest operators is that "..." represents both of them. Naming and functionality depends on how and where it is being used.

Spread Operator

As the name suggests it spreads out the values.

For example, we have an array of numbers and we need individual elements. We can use spread operator to grab the individual elements.

const add = (a,b) =>{
    return a +b
}

var myParams = [5 , 4]
// spread operator 
console.log(add(...myParams)) // 9

Rest Operator

Rest operator is used in grabbing multiple values. It simply converts all elements into an array.

const add = (...args) => {
    console.log(args)    //[ 1, 2, 3, 4, 5 ]
    let sum = 0;
    for (const arg of args){
        sum += arg
    }
    return sum
}

console.log(add(1,2,3,4,5))    //15

Another Example in which we can specify mandatory parameters and the other parameters (no of arguments not known) using rest operator.

const calc = (a, b, ...args) => {
    // console.log(args)
    let mul = a * b
    let sum = 0;
    for (const arg of args){
        sum += arg
    }
    return [mul, sum]
}

console.log(calc(1,2,3,4,5))    //[2, 12]

Multiplication of 1 and 2 = 2

Sum of 3, 4 and 5 = 12

The End

I hope you enjoyed the article and had a good learning experience.

Follow for more articles and keep sharing👩

Keep coding

Linkedin

hashnode blogs

Did you find this article valuable?

Support akshita garg by becoming a sponsor. Any amount is appreciated!