Alert !!! First Post
Did you ever think about what was the world(javascript) before the rest operator? Yes, I'm talking about the (...) introduced in ES6.
function multiplyBy2(...values){
for(let i=0;i<values.length;i++){
console.log(2*values[i]);
}
}
multiplyBy2(10,20,30,40,50)
// Output
20
40
60
80
100
Did you ever think about 🤔 what technique was used before to create variadic functions?
One possible solution which comes to our(mine) mind first is that, instead passing of values, we pass an array directly. Obviously nothing wrong with that.
But there's the story of a saviour, which you might not have heard about.
arguments is an array-like object accessible inside functions that contains the values of the arguments passed to that function.
MDN
In simple words, it was used to create the functions where you need to pass the arguments more than the function was supposed to accept.
Let's understand more about it.
function multiply(a,b){
return arguments[0] * arguments[1]
}
console.log(multiply(4,5))
// output
20
Nice. But, so what you just replace the a and b with "arguments". Let's extend the example a bit.
function multiply(a,b){
return arguments[0] * arguments[1] * arguments[2]
}
console.log(multiply(4,5,6))
// output
20
When you are using the arguments
object to access the passed value, you do not need to declare parameters in function definition a, b
.
⚠️ arguments[0]
seems like we are accessing an array using index but we're not. We(MDN) already said it's an array-like object
.
function multiply(){
let result = 1;
//since arguments not an array but an object
let values = Object.values(arguments);
for(let i = 0; i < values.length; i++){
result *= values[i];
}
return result;
}
console.log(multiply(4,5,6));
Output
20
Right!
What's the issue then
But you might not have seen it often. The problem arises when we use it with arrow functions. The arguments
object is the built-in part of the function
. So, it's not accessible in the arrow functions.
const multiply = (a,b) => {
return arguments[0] * arguments[1]
}
console.log(multiply(4,5))
// Output
Uncaught ReferenceError: arguments is not defined
Note: In modern code, rest parameters should be preferred
MDN
Summary
-
arguments
object give you access to the arguments passed to the function - Unaccessible inside arrow functions
- Use rest parameters when creating variadic => functions.
Top comments (0)