Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there such a thing as not enough arguments in JavaScript? Why?

In JavaScript, it is valid to not pass some arguments to some functions. They get treated as undefined which is essential to many functions' logic.

I've read about this error called "Not enough arguments". Is it standard? Why does it exist?

function foo(a) {
  // yada yada
}
try {
  foo();
} catch (e) {
  console.log(e.name);
}

^ this code didn't throw anything on Firefox and Chrome.

like image 962
batman Avatar asked Dec 25 '22 20:12

batman


1 Answers

I've read about this error called "Not enough arguments".

This is not a standard langauge-level error; it's an API-level error. That is, JavaScript generally does not care if the number of actual arguments passed to a function matches the function's formal arguments. However, a particular API written in JavaScript might care about number of arguments.

For example, Firefox's addEventListener function (part of Firefox's DOM API) can throw a "Not enough arguments" error because the specification for addEventListener is defined to expect at least two arguments.

You can test the number of actual arguments passed to a function with the arguments object:

function foo(a, b) {
    if(arguments.length < 2) {
        throw TypeError("Not enough arguments; two expected");
    }

    if(arguments.length > 2) {
        throw TypeError("Too many arguments; two expected");
    }

    if(arguments.length > 10) {
        throw TypeError("Way too many arguments; did you even read the docs?");
    }
}

Your code must detect the number of arguments and actively throw an error if you want argument mismatch to result in an error. This version of foo will throw a TypeError that gets caught in your catch block.

Remember, however, that the error has nothing to do with the number of formal arguments of foo. I could have defined it as function foo(a,b,c), but still enforced a two-argument requirement by checking arguments.

like image 63
apsillers Avatar answered Dec 28 '22 09:12

apsillers