Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `Object.length === 1` in JavaScript as part of browsers?

Tags:

javascript

I'm troubleshooting something in Angular that ends up checking Object.length. The result is 1. The string representation of it does not show any arguments. I get that the first argument is used.

var obj = new Object({ a : 27 });

Object's constructor function lists the argument as optional.

document.write(Object.length);

So why/how is it counted?

like image 952
Daniel A. White Avatar asked Jan 09 '23 15:01

Daniel A. White


1 Answers

The length of a function is the number of declared arguments, excluding any rest parameter.

From the MDN:

length is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters. This number does not include the rest parameter.

There's exactly one for the Object constructor, the optional wrapped value.

Moreover, in the specific case of the Object function, the ES spec explicitly mandates it should have a length of 1:

Besides the internal properties and the length property (whose value is 1)

(it seems to do so for all functions taking a rest parameter, like Array or fromCharCode)

Note that the (implementation dependent) string representation of native functions in browsers doesn't necessarily show the formal arguments.

like image 128
Denys Séguret Avatar answered Jan 13 '23 13:01

Denys Séguret