Advertisement
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,
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); //3But 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.
1function sum(a, b = 2, c = 3) {
2
3return a + b + c;
4}
5
6console.log(sum.length); // 12. Rest params: The rest parameters are excluded with in length property.
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); // 23. Destructuring patterns: Each destructuring pattern counted as a single parameter.
1function func([a, b], { x, y }) {
2
3console.log(a + b, x, y);
4}
5
6console.log(func.length); // 2Note: The Function constructor is itself a function object and it has a length property of 1.
Advertisement
JavaScript Coding Exercise 43
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement