Sitemap
rahul singh tomar

rahul singh tomar

Front end developer

Rest Operator in JavaScript

2 min readJul 30, 2024

The rest operator was introduced in ES6, which you should now know is the sixth edition of the ECMAScript Standard, released in 2015.

The rest operator in JavaScript allows a function to take an indefinite number of arguments and bundle them in an array, thus allowing us to write functions that can accept a variable number of arguments, irrespective of the number of parameters defined. These types of functions in JavaScript are called variadic functions .

The rest parameter always returns an array so we can use any array methods that the JavaScript provides us on it.

function intro(...detail){
console.log(detail) // ["rahul", "from" ,"gwalior"]
}
intro("rahul","from","gwalior");

in above example we can use all properties of array.

function intro(name,...detail){
console.log(name)//rahul
console.log(detail) // ["from" ,"gwalior"]
}
intro("rahul","from","gwalior");

You can see on line two, the name is being printed out, which is Rahul, and on line three detail

Get rahul singh tomar’s stories in your inbox

Join Medium for free to get updates from this writer.

only contains the rest of the parameters and that’s why it’s called the rest operator.

function intro(name,...detail,...city){
}
//error
function intro(name,...detail,city){
}
//error

The rest operator is always given as the last parameter and a function definition can have only one rest operator else the code throws a Syntax Error error .

Why we need rest operator

// function without rest parameter
function sum(x, y) {
return x + y;
}
console.log(sum(2, 3)); //5
console.log(sum(2, 3, 4, 5, 6)); //5
console.log(sum(2,)); //NaN

in above examples we can see that if we did not use rest operator , it ignores others arguments and takes only required one.

convert array from arguments

function sum(a, b, c) {

//slice selects a part of an array and returns the new array
let changedToArray = Array.prototype.slice.call(arguments);
}
sum(1,2,4)
function myFun(one, two, ...manyMoreArgs) {
// here '...manyNoreArgs' is the rest parameter

console.log("one: ", one); //one: HTML
console.log("two: ", two); //two: CSS

// empty array will be created
console.log("manyMoreArgs: ", manyMoreArgs); //manyMoreArgs: []
}

myFun("HTML", "CSS");

in above example empty array is created if no arguments left .

To calculate length of arguments

function myFun(...myArgs) {
console.log(myArgs.length);
}

myFun(); //0
myFun("HTML"); //1
myFun(10, 15); //2

--

--