Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `Array.length`, `Function.length`, `String.length`, etc return 1?

Tags:

javascript

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?

like image 695
zealoushacker Avatar asked Nov 22 '25 07:11

zealoushacker


1 Answers

Function.length itself is the answer:

Specifies the number of arguments expected by the function. MDN JS Ref: Function.length

When we write Function.length we are asking the Function constructor to tell us the number of formal, named parameters ("optional" - i.e. non-formal - parameters are accessed via the arguments property in the function body). Because the Function constructor expects exactly 1 formal named parameter, the result is 1:

new Function ([arg1[, arg2[, ... argN]],] functionBody)

functionBody is the single formal named parameter. Therefore Function.length is 1.

like image 67
zealoushacker Avatar answered Nov 24 '25 20:11

zealoushacker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!