DEV Community

Devraj Sawant
Devraj Sawant

Posted on

1. Rest Parameter & why do we need it

quick intro - Hey, I am a frontend dev trying to level up, and to do that i have decided to daily deep dive into one concept of JS/TS and share what i have learnt so others can engage, cross question and grow.

WHY ...REST ?
the problem before REST was one must know the exact number of parameters needed to be passed to the function, and if you don't know you need to use 'argument' object.

argument object :
argument object is a built-in object of JS which is available inside regular function and it holds all the argument passed to that functions, it is kind of dynamic array but it's not an array
it has index and length , but you can't use other array methods on it such as map,filter,etc

function showArguments() {
  console.log(arguments[0]) // 10
  console.log(arguments[1]) //20
}

showArguments(10, 20); 
Enter fullscreen mode Exit fullscreen mode

Drawbacks :

  1. not a real array so you can't use map,filter,etc other array methods
  2. arguments work only on normal functions not on arrow functions
  3. store parameters on basis of index and not names
  4. hard-to-read code

WHAT IS REST ?
Rest is a special parameter which is used to store all/remaining parameters into real array just like 'arguments' did

then why use rest?

  1. Rest is real array so you can use all the array methods with it which was not possible with arguments
  2. Rest works with arrow functions too unlike 'arguments'
  3. rest parameters can be given any naming, improving readability
  4. arguments contain only all the parameters passed but rest contains only the extras (other than explicitly defined)

example of Rest :

function greet(firstName, lastName, ...hobbies) {
  console.log("First Name:", firstName); // ABC
  console.log("Last Name:", lastName); // XYZ
  console.log("Hobbies:", hobbies); // ["Coding","Gaming","reading"]
}

greet("ABC", "XYZ", "Coding", "Gaming", "Reading");
Enter fullscreen mode Exit fullscreen mode

Top comments (0)