Be the first user to complete this post

  • 0
Add to List

Getting the parameters and arguments of a javascript function

If you're reading this post, I assume you have a reference to a function in javascript and you want to find out know how many arguments it takes. Turns out every function has a length property that represents the number of parameters defined as per its function defintion. Here's a simple example

function barOne() {}
function barTwo(arg) {}

function foo(f) {
    if (
        typeof f === 'function' &&
        f.length > 0 // Here's your secret sauce
    ) {
        console.log('Passed function defines some parameters');
    } else {
        console.log('Passed function does not define any parameters');
    }
}

foo(barOne);
foo(barTwo);
I first became curious about this when writing mocha tests and learnt that the describe and it blocks in mocha behave synchronously when the function passed takes a done callback as an argument. NOTE: This is not to be confused with the arguments variable within a function. The arguments variable is local to the function scope. Its an array like object that represents the actual number of arguments the function was invoked with. It may or may not be equal to the number of arguments as per function definition. Lets take another example to demonstrate the difference
function barOne() { // No arguments as per declaration
    console.log(arguments.length);
}

function barTwo(arg1) { // 1 argument as per declaration
    console.log(arguments.length);
}

console.log(barOne.length); // Prints 0
barOne(); // Prints 0
barOne('hello') // Prints 1
barOne('hello', 'world') // Prints 2

console.log(barTwo.length); // Prints 1
barTwo(); // Prints 0
barTwo('hello') // Prints 1
barTwo('hello', 'world') // Prints 2
Hope this comes in handy!



Also Read:

  1. Getting started with localStorage vs sessionStorage in html5
  2. position:fixed
  3. Progressive enhancement vs Graceful degradation
  4. Promise javascript examples
  5. box-sizing
  6. Difference between async and defer attributes in script tags
  7. css: margin does not work
  8. gzip compress and cache api response in express