Member-only story
Implement a function, to return the number of parameters a function expects.
1 min readApr 9, 2025
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
- 👏 Please clap for the story and follow me 👉
- 📰 View more content on Coding and System Design Interviews
- 🔔 Follow me: LinkedIn!
I know there would always be something to improve. Please feel free to share your thoughts