Member-only story

Implement a function, to return the number of parameters a function expects.

function foo() {}
function bar(a) {}
function baz(a, b) {}

functionLength(foo); // 0
functionLength(bar); // 1
functionLength(baz); // 2

Solution

All function instances have a length property which indicates the number of parameters expected by the function.


/**
* @param {Function} fn
* @return {number}
*/
export default function functionLength(fn) {
return fn.length;
}

Notes

The length property excludes the rest parameter and only includes parameters before the first one with a default value.


function foo(a, b = 2) {}
foo.length; // 1

function bar(a = 1, b = 2) {}
bar.length; // 0

function baz(...args) {}
baz.length; // 0

Thanks for reading

I know there would always be something to improve. Please feel free to share your thoughts

--

--

Sonika | @Walmart | Frontend Developer | 11 Years
Sonika | @Walmart | Frontend Developer | 11 Years

No responses yet