What is the length of the function in js
- 2021-11-13 06:39:26
- OfStack
Why
How much is it?
Number of formal parameters
Default parameter
Residual parameter
Summarize
Preface
Today, I will tell you about length of function, and how to calculate it. I hope everyone can learn something from it and consolidate the foundation.
Why
Why did I think of this knowledge point? Because last night, in a group, a classmate was discussing a ByteDance interview question
123['toString'].length + 123 = ?
To tell the truth, I didn't answer this question at first. Actually, I know that the interviewer wants to test the toString method on the Number prototype, but I am stuck in the problem of what is the length of the toString function. That's why today's article came into being
How much is it?
Number of formal parameters
Let's take a look at the following example
function fn1 () {}
function fn2 (name) {}
function fn3 (name, age) {}
console.log(fn1.length) // 0
console.log(fn2.length) // 1
console.log(fn3.length) // 2
It can be seen that function has as many formal parameters as length. But is this really the case? Keep looking down
Default parameter
If there are default parameters, what is the length of the function?
function fn1 (name) {}
function fn2 (name = ' Lin 3 Heart ') {}
function fn3 (name, age = 22) {}
function fn4 (name, age = 22, gender) {}
function fn5(name = ' Lin 3 Heart ', age, gender) { }
console.log(fn1.length) // 1
console.log(fn2.length) // 0
console.log(fn3.length) // 1
console.log(fn4.length) // 1
console.log(fn5.length) // 0
It shows that length of function is the number of parameters before the first one has the default value
Residual parameter
In the formal parameters of the function, there are residual parameters. If there are residual parameters, how will it be calculated?
function fn1(name, ...args) {}
console.log(fn1.length) // 1
It can be seen that the remaining parameters are not included in the calculation of length
Summarize
Before concluding, publish 123 ['toString']. length + 123 =? The answer is 124
To sum up, length is an attribute value of a function object, which refers to how many parameters the function has to pass in, that is, the number of formal parameters. The number of formal parameters does not include the number of remaining parameters, but only the number of parameters before the first one has the default value