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);
Drawbacks :
- not a real array so you can't use map,filter,etc other array methods
- arguments work only on normal functions not on arrow functions
- store parameters on basis of index and not names
- 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?
- Rest is real array so you can use all the array methods with it which was not possible with arguments
- Rest works with arrow functions too unlike 'arguments'
- rest parameters can be given any naming, improving readability
- 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");
Top comments (0)