While teaching my JavaScript class yesterday, my students and I came across some interesting functionality that I thought might be worth capturing in a question and the answer I’ve come to.
Typing Array.length in the JS console in chrome returns 1.
Likewise, Function.length returns 1. This is important because:
Every function in JavaScript is actually a Function object. (MDN JS Ref: Function)
Thus, Object.length and likely all other native objects will and should return 1 as the value of the length property.
So, finally why is this behavior occurring?
Function.lengthitself is the answer:When we write
Function.lengthwe are asking theFunctionconstructor to tell us the number of formal, named parameters (“optional” – i.e. non-formal – parameters are accessed via theargumentsproperty in the function body). Because theFunctionconstructor expects exactly 1 formal named parameter, the result is1:functionBodyis the single formal named parameter. ThereforeFunction.lengthis1.