Unlike Java, JS will not throw any errors if the way function is declared and called is different. So there are 2 scenarios when developer passes wrong number of parameters. Either too many or too less
If too many:
Ex: function xyz(x, y,z){
console.log(x);
}
xyz();
// output will be undefined
So, to tackle this potential issue when other developers pass more arguments to a method than it can accept we can use either arguments or spread.
Ex
function abc(a, b,c){
console.log(arguments);
}
// arguments is keyword and will return a,b,c or whatever arguments passed to abc function.
Works a bit similar to this keyword can access it through arguments[n]
Another way is using spread:
Ex.:
function restParam(parameter1, …restArgs){
console.log(restArgs.length); // Logs the number of arguments that do not have a corresponding parameter
console.log(restArgs[2]); // Logs the 3rd argument after the number of arguments that do not have a corresponding parameter
}
restParam(1,2,3,4,5);
// Log would be as follows
// 4
// 4
// 4 is the number of arguments that do not have a corresponding parameter
// 4 is the 4th 3rd argument after the number of arguments that do not have a corresponding parameter
Second way is preferred, because arguments only return array like collection. The keyword is “like”, so some array methods won’t work. (arguments.length and arguments[n] will still work )
Oh, yeah. In the case if there are less parameters passed
If too less:
just assign the functions parameters to a default variable:
fuction zzz(a, b,c){
a= a || “a”;
b=b || 7;
c = c || 10;
}