A JavaScript Interview Question That Mistakes People
Are you ready to respond immediately? Stop before you answer. Perhaps you are already familiar with type changes, but how do we calculate the length of a string function? And How is a normal function's length determined, too?
In JavaScript, the length property of a function represents the number of arguments expected by the function when it was declared. It calculates the number of expected arguments, does not include the remaining parameter operator (...) after it, nor considers the default parameter. This property is often used in reflection and some functional programming scenarios to understand how many arguments a function is expected to receive.
Example Explanations
1. Function without Any Parameters
function withoutParams() {}
console.log(withoutParams.length); // Outputs: 0
As there are no parameters defined for this function, its length property is 0.
2. Single-parameter Function
function singleParam(a) {}
console.log(singleParam.length); // Outputs: 1
This function defines a single parameter, so its length property is 1
3. A Multi-Parameter Function
function multipleParams(a, b, c) {}
console.log(multipleParams.length); // Outputs: 3
This function has a length property of three because it defines three parameters.
4. Function with Default Parameters
function defaultParams(a, b = 2, c) {}
console.log(defaultParams.length); // Outputs: 1
When a function has default parameters, the length property is counted up to the first default parameter. However in this example three parameters are defined, because the second parameter is a default parameter, the value of length is 1.
5. Function with Rest Parameters
function restParams(a, b, ...rest) {}
console.log(restParams.length); // Outputs: 2
For functions that use the rest parameter operator, the length property counts only the parameter before the rest of the parameters. In this example, although the function can accept an infinite number of arguments, the value of length is 2, counting only the parameters before ( …rest ).
These examples show that the 'length' property of a function provides a simple way to see how many arguments a function expects to receive, which can be useful in some programming operations.
In JavaScript, every number inherits methods from the Number prototype, including toString. When you access 123['toString'], you're actually accessing the toString method of the number 123. JavaScript functions include a 'length' property that describes the number of expected parameters. Since Number.prototype.toString only accepts one parameter ( the radix) ,its length is 1. As a result, in JavaScript.
- '123['toString'].length' would equal 1.
- Adding 123 to this gives 1 + '123', which equals '1123'.
- So, 123['toString'].length + '123' would result in '1123'.