JavaScript Rest Parameter

Masfikul Alam
2 min readAug 19, 2020

--

Confused between Spread and Rest? Let’s clear it out!

Talking about rest, it is called a parameter. And we all know where parameters are used. Exactly! Functions. Rest parameter are used in functions. Wanna know where spread operators are used? check out my article on Spread Operator. We’re gonna discuss mostly about rest parameter here.

ES6’s rest parameter is like a alternative of ES5’s arguments object in function but a bit more flexible. We used to use the arguments object in functions when we didn’t know how many arguments are going to be passed on to the function. For example -

function howManyArgs() {
return arguments.length;
};

Here if we call the function with any amount of arguments its gonna return us the amount. Like if we say howManyArgs(11,44,22,55,66,99) it’s gonna return 6.

But one of the boundaries of arguments object is we cannot use it in arrow functions. If we try to use the same example in arrow functions, it would throw an error. Another problem is, though the arguments object is like an array, we cannot use array methods like push(), pop(), slice() on it. Same issue, throws error.

This is where we need our rest parameter which is usable with all types of functions. We can even name those arguments after putting three dots ...
For example -

const sayHello = (...names) => {
for(let i=0; i<names.length; i++) {
console.log('hello ' + names[i])
}
};

This sayHello function with a rest parameter is going to loop through all the arguments and print hello with the name. Now if we call the function sayHello('david', 'john', 'cassey', 'mica'), guess what’s it gonna print!

// hello david
// hello john
// hello cassey
// hello mica

This is working like the arguments object in ES5 but working in arrow functions! The interesting thing is, we can use even array methods on them. Let’s say -

function sayBye(...names) {
names.map(name => console.log('good bye ' + name);
};

Now calling the function sayBye('david', 'john', 'cassey', 'mica'). And this time, where the arguments object would throw an error, our rest parameter takes the .map() method and prints -

// good bye david
// good bye john
// good bye cassey
// good bye mica

So that’s it with our ES6 rest parameter. We saw how it is more flexible than the ES5 arguments object. Make sure to use it. Pulling the conclusion here. Take care. Assalamualaikum :)

--

--

Masfikul Alam
Masfikul Alam

Written by Masfikul Alam

0 Followers

Frontend Web Developer

No responses yet