JS Coding Questions Logo
JS Coding Questions
#471💼 Interview💻 Code

How to find the number of parameters expected by a function?

Advertisement

728x90

The function's object has a length property which tells you how many formal parameters expected by a function. This is a static value defined by the function, not the number of arguments the function is called with(arguments.length). The basic usage of length propery is,

javascript
1function multiply(x, y) {
2
3return x * y;
4}
5
6function sum(a, b, c) {
7
8return a + b + c;
9}
10
11console.log(multiply.length); //2
12
13console.log(sum.length); //3

But there are few important rules which needs to be noted while using length property.

1. Default values: Only the parameters which exists before a default value are considered.

javascript
1function sum(a, b = 2, c = 3) {
2
3return a + b + c;
4}
5
6console.log(sum.length); // 1

2. Rest params: The rest parameters are excluded with in length property.

javascript
1function sum(a, b, ...moreArgs) {
2
3let total = a + b;
4
5for (const arg of moreArgs) {
6
7total += arg;
8}
9
10return total;
11}
12
13console.log(sum.length); // 2

3. Destructuring patterns: Each destructuring pattern counted as a single parameter.

javascript
1function func([a, b], { x, y }) {
2
3console.log(a + b, x, y);
4}
5
6console.log(func.length); // 2

Note: The Function constructor is itself a function object and it has a length property of 1.

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 43

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
471of476
How to find the number of parameters expected by a function? | JSCodingQuestions.com