JavaScript Rest Parameter Explained

JavaScript Rest Parameter Explained

Rest pattern and Rest parameters

The rest pattern looks exactly like the spread operator so it has syntax with three dots but it does the opposite of the spread operator.

Do check my previous blog where I talked about the spread operator

The rest pattern uses the exact same syntax however to collect multiple elements and condense them into an array.

Now let's get our hands dirty by writing some code,

// This is a spread operator since we are using it on right side
const x = [4,5,6,...[8,9]] 
// This is a rest pattern since we are using it on left side 
const [a,b, ...others] = [1,2,3,4,5]
console.log(a,b,others) // 1,2, [3,4,5]

In the above example, we are using the rest pattern and getting the output a, b and rest of the elements that we did not select into this a and b array.

Let's analyze what's happening here,

  1. First and second elements become the first and second variables
  2. Every other element are packed into this new array others using rest pattern

Let's see one more example to understand much clearly,

function sum(...args) {
    let total = 0;
    for (const a of args) {
        total += a;
    }
    return total;
}

sum(1, 2, 3); // 6

In this example, args is an array, therefore, we could use the for..of loop to iterate over its elements and sum them up. Please note that the rest parameter must be the last parameter of the function.

Here is the Browser Compatability :

Everything demonstrated above will work in all browsers except a few and any browser Microsoft has made for the last 20 years is hot garbage without exception.

Screenshot 2021-07-19 at 3.29.23 PM.png

You can use the Babel Object Rest Spread package in whatever you’re using to build. If you’re using this functionality extensively, make sure you test carefully in every browser if you care to support it. I won’t tell anyone if you don’t 😉.


Thanks for reading my blog & Let's connect! 🙌🏼

Follow me for more similar articles :D

Feel free to subscribe to my Youtube Channel & Follow me on Twitter <3