Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get argument count (or even names) of javascript function object

I want to evaluate callback function before accepting it. This means I need to know at least the count of accepted argumens - if count doesn't match, I'll leave warning in console. But I can't find out, whether a javascript function object has a property that would help me get that information.
So can this be achieved without parsing function as string (not worth it)?

like image 608
Tomáš Zato - Reinstate Monica Avatar asked Aug 24 '13 19:08

Tomáš Zato - Reinstate Monica


People also ask

How do you count the number of times a function is called in JavaScript?

count() The console. count() method logs the number of times that this particular call to count() has been called.

How do you find the number of arguments in JavaScript?

The arguments. length property contains the number of arguments passed to the function.

Does JavaScript functions check for the number of arguments received?

JavaScript functions do not perform type checking on the passed arguments. JavaScript functions do not check the number of arguments received.

How can you get the type of arguments passed to a function JavaScript?

You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0 . You can use arguments.length to count how many arguments the function was called with.


1 Answers

A function has a length property which tells you how many named arguments it accepts. Note however, a function can use the arguments variable to access variables, even if it doesn't name them; length doesn't cater for this (nor is there an alternative which does).

function foo(a, b) {
    for (var i=0;i<arguments.length;i++) {
        console.log(arguments[i]);
    }
}

console.log(foo.length); // reports 2, even though `foo` can access all your arguments!
like image 174
Matt Avatar answered Oct 24 '22 11:10

Matt