Skip to content Skip to sidebar Skip to footer

Finding The Number Of Function Parameters In JavaScript

Possible Duplicate: Get a function's arity Say I have: function a(x) {}; function b(x,y) {}; I want to write a function called numberOfParameters that returns the number of par

Solution 1:

function f(x) { }
function g(x, y) { }

function param(f) { return f.length; }

param(f); // 1
param(g); // 2

Disclaimer: This should only be used for debugging and auto documentation. Relying on the number of parameters that a function has in it's definition in actual code is a smell.

.length


Solution 2:

Just use length?

a.length // returns 1
b.length // returns 2

Solution 3:

Like most languages, there's more than one way to do it (TMTOWTDI).

function foo(a,b,c){
   //...
}
  1. Length method of Function object:

    foo.length();                                  // returns 3
    
  2. Parse it (using test):

    args = foo.toString();
    RegExp.lastIndex = -1;                         // reset the RegExp object
    /^function [a-zA-Z0-9]+\((.*?)\)/.test(args);  // get the arguments
    args = (RegExp.$1).split(', ');                // build array: = ["a","b","c"]
    

    This gives you the ability to use args.length, and list the actual argument names used in the function definition.

  3. Parse it (using replace):

    args = foo.toString();
    args = args.split('\n').join('');
    args = args.replace(/^function [a-zA-Z0-9]+\((.*?)\).*/,'$1')
               .split(', ');
    

Note: This is a basic example. The regex should be improved if you wish to use this for broader use. Above, function names must be only letters and numbers (not internationalized) and arguments can't contain any parentheses.


Post a Comment for "Finding The Number Of Function Parameters In JavaScript"