19

When I do

for (var i in window) console.log(window[i])

I get a list of window properties and methods

Howver when I do the same for "Math" object, I get nothing.

typeof "window" == typeof "Math"

returns TRUE, so I do not see a reason why my loop is not working.

It's strange as if I write directly Math['E'] I get the value of constant E.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
lukas.pukenis
  • 13,057
  • 12
  • 47
  • 81

4 Answers4

19

Not all object properties are iterable. You'll only get iterable properties in a for..in loop.

Since most properties of window (which happens to be the global object) are user-defined global variables, they are enumerable.

In modern JavaScript engines you can use Object.getOwnPropertyNames(obj) to get all properties, both enumerable and non-enumberable:

>>> Object.getOwnPropertyNames(Math)
["toSource", "abs", "acos", "asin", "atan", "atan2", "ceil", "cos", "exp", "floor", "log", "max", "min", "pow", "random", "round", "sin", "sqrt", "tan", "E", "LOG2E", "LOG10E", "LN2", "LN10", "PI", "SQRT2", "SQRT1_2"]

See Is it possible to get the non-enumerable inherited property names of an object? for more details.

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
8
["max", "ceil", "SQRT2", "PI", "pow", "log", 
"LOG2E", "tan", "sqrt", "exp", "random", "min",
"floor", "atan2", "cos", "atan", "acos", "abs", 
"round", "asin", "LN2", "LOG10E", "sin",
"E", "SQRT1_2", "LN10"].forEach( function(key ) {
    if( Math[key] ) {
        console.log( key, Math[key] );
    }
});

You can get a list of those keys in a modern browser with Object.getOwnPropertyNames( Math ); The above works in all noteworthy browsers provided you shimmed .forEach

Esailija
  • 138,174
  • 23
  • 272
  • 326
4
console.log(Object.getOwnPropertyNames(Math));
gopi1410
  • 6,567
  • 9
  • 41
  • 75
0

What about this ?

let a = Object.getOwnPropertyNames(Math);
a.forEach((element) => console.log(element));
toyota Supra
  • 3,181
  • 4
  • 15
  • 19
eliazoura
  • 1
  • 2