Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I get properties count of navigator object in JavaScript?

Run in your browser (ES5+)

var propCount = Object.keys(navigator).length;
console.log(propCount); // 0

If you do it for a plain object like that

let obj = {
    foo: 'bar',
    breaking: 'bad'
}

let propCount = Object.keys(obj).length;

console.log(propCount); // 2

Why does it happen?

Sorry if it might relate to another problem like when Object.keys(obj) is only counting it for simple objects which do not contain functions/arrays, but this the 1st time I encountered with it.

And would like to know the reason of it.

like image 671
knitevision Avatar asked May 14 '16 17:05

knitevision


People also ask

How do you know how many keys an object has?

keys() method and the length property are used to count the number of keys in an object. The Object. keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"] . The length property returns the length of the array.

How many properties can an object have JS?

How many properties can an object have JS? Summary. JavaScript objects have two types of properties: data properties and accessor properties.


2 Answers

Object.keys() function returns properties of the object that are directly assigned to it. If you do the following:

console.log(navigator.hasOwnProperty('permissions')); // false

If you want to see properties of navigator do the following:

for(let i in navigator){
    console.log(i);
}

It will list all the properties of navigator object because for ... in ... loop includes object's prototype.

like image 83
Azamantes Avatar answered Sep 28 '22 04:09

Azamantes


That's because most properties of navigator are set on the Navigator prototype, which the navigator instance inherits, and Object.keys only returns the properties set on the navigator object itself.

You can get those properties from the prototype with this:

Object.keys(Object.getPrototypeOf(navigator));

On a side note, Firefox has the following properties in the navigator object itself:

[ "doNotTrack", "mozPay", "mozContacts", "mozApps" ]
like image 30
Alexander O'Mara Avatar answered Sep 28 '22 05:09

Alexander O'Mara