Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Getting the parameters and arguments of a javascript function

If you’re read­ing this post, I assume you have a ref­er­ence to a func­tion in javascript and you want to find out know how many argu­ments it takes.

Turns out every func­tion has a length prop­erty that rep­re­sents the num­ber of para­me­ters defined as per its func­tion defintion.

Here’s a sim­ple 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 curi­ous about this when writ­ing mocha tests and learnt that the describe and it blocks in mocha behave syn­chro­nously when the func­tion passed takes a done call­back as an argument.

NOTE: This is not to be con­fused with the arguments vari­able within a func­tion. The argu­ments vari­able is local to the func­tion scope. Its an array like object that rep­re­sents the actual num­ber of argu­ments the func­tion was invoked with. It may or may not be equal to the num­ber of argu­ments as per func­tion definition.

Lets take another exam­ple to demon­strate 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!


Ryan Sukale

Ryan is just a regular guy next door trying to manage his life and finances.