16

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)?

1 Answer 1

33

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!
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Is there a full specification of function object properties and methods? I failed to find one.
@Tomas: the link in my answer should provide this.
NOTE: default parameters don't count to length. Check yourself: [((a) => {}), ((a=1) => {})].forEach(f => console.log(`f="${f.toString()}", length=${f.length}`))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.