2

Is there a tool that can help me detect when a javascript function is being passed too few arguments? As far as I can tell, neither JSLint nor JSHint provides this feature.

Just be make it clear, if I write:

some_method = function(x,y) {
  // ..do stuff
}
some_method(2);

I would like to be warned, that I might have to pass in another argument.

mollerhoj
  • 1,298
  • 1
  • 10
  • 18
  • You would probably want to validate what is passed in anyway (such as checking for null/undefined values, etc), and then just handle invalid input appropriately. – forgivenson Aug 18 '14 at 13:47
  • 2
    Note that functions in JavaScript are variadic, and there's no magic way for JSHint or JSLint to know that you are always using exactly 2 arguments to `some_method`: for example, how would it know whether or not the second argument was optional? – Peter Olson Aug 18 '14 at 13:52
  • i dont think this could be really validated without actually creating the object in memory. you could resort to checking the passed values inside the function. – Prabhu Murthy Aug 18 '14 at 13:54

2 Answers2

1

You can't do that, all parameters are always optional and you can pass an indefinite amount of parameters to a parameterless function (through the arguments array).

But you can use the arguments array to test your own methods manually. You would have to add it to each method individually, since you can't reflect the amount of arguments in your method signature. So for this specific case you would use:

function test(x, y) {
  if (arguments.length !== 2)
    {
      console.log('error, invalid amount of args');
    }
}

test(1); // this will trigger the console.log and type the error.

If you really need parameter checking you could use something like TypeScript, where parameters are required by default.

Brunis
  • 1,073
  • 8
  • 12
  • 1
    The question was not really on how to implement this manually, but how to get notified when checking the code using tools such as JSLint or JSHint … – CBroe Aug 18 '14 at 14:12
  • You can't do that, all parameters are always optional and you can pass an indefinite amount of parameters to a parameterless function (again, through the arguments array). – Brunis Aug 18 '14 at 14:16
  • 1
    _“You can't do that”_ – well then your answer should state that, instead of answering a completely different question … – CBroe Aug 18 '14 at 14:21
-1

In case you want to get some optional param in function, you can passing the params as array, and can validate each array's value. Like this:

function action(param)
{
    var total_params = param.length;
    console.log(param);

    // do stuff
}

action(Array('param01',02, true, 'param04'));
Helam.Dev
  • 86
  • 2
  • 1
    This is buggy for passing in one numerical parameter: `Array(5)` creates an array with 5 empty elements. You should be using an array literal instead. – Peter Olson Aug 18 '14 at 15:41