Preface
Today I will tell you how the length of function is calculated. I hope everyone can learn 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 an interview question from ByteDance
123['toString'].length + 123 = ?
To be honest, I didn't answer this question at the beginning. Actually, I know that the interviewer wants to take the toString method on the Number prototype, but I am stuck on the problem of how long the toString function is. That's why today's article comes from
How much exactly?
Number of formal parameters
Let's take a look at the following example
function fn1 () {} function fn2 (name) {} function fn3 (name, age) {} () // 0 () // 1 () // 2
It can be seen that the function has many formal parameters and the length is as much. But is this really the case? Keep reading
Default parameters
If there are default parameters, what is the length of the function?
function fn1 (name) {} function fn2 (name = 'Lin Sanxin') {} function fn3 (name, age = 22) {} function fn4 (name, age = 22, gender) {} function fn5(name = 'Lin Sanxin', age, gender) { } () // 1 () // 0 () // 1 () // 1 () // 0
Explanation: the length of function is the number of parameters before the default value.
Remaining parameters
In the formal parameters of a function, there is still the remaining parameters. So if there are residual parameters, how will it be calculated?
function fn1(name, ...args) {} () // 1
It can be seen that the remaining parameters are not included in the calculation of length
Summarize
Before summarizing, the answer to 123['toString'].length + 123 = ? is 124
The summary is: length is an attribute value of the function object, which refers to how many parameters that must be passed in the function, that is, the number of formal parameters. The number of formal parameters does not include the remaining number of parameters, only includes the number of parameters before the first one with the default value.
This is the end of this article about the length of a function in js. For more related content on length of a js function, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!