javascriptobjectfor-in-loopwindow-object

Iterating through window object using for in loop


Basically i want to print all properties on the window object, i am using:

for(var k in window){
document.write("window object = "+ Object.getOwnPropertyNames(window[k])+ "<br>");
}

I get a weird output with that code.I want to print each property on a new line using for in,how can i do that? thanks!


Solution

  • Why are you using for/in, and why are you using document.write?

    The first comes to us from legacy JavaScript, from a time before we had proper object key iteration baked right into the JavaScript language, and because it is a bad idea(tm) depending on what you're iterating, with more appropriate modern functions available, should not be used anymore. The second is an ancient low level function that absolutely does not do what you think it does and should never be used in modern code. It is incredibly dangerous, and any tutorial that still uses it that told you to use it should be ashamed of itself.

    So: solve your problem with modern JS, not legacy or even obsolete JS. To get all the keys for an object, use Object.keys(...) and use the Console API (console.log, etc.) if you just want to see what's in your object.

    Object.keys(window).forEach( key => {
      let type =  typeof window[key];
      console.log(`${key} (${type})`);
    });
    

    Done.

    Every window property and function listed on its own line, with the type listed because you usually want to know about that. Also note that array.forEach call: JavaScript has a ton of super useful array functions, well worth giving the available functions a quick read through. Finally, this code uses an arrow function, which is a rather nice new piece of JS syntax. You don't have to use it, but it's super compact without sacrificing readability. It also uses a template literals rather than string literals, which are another very handy modern JS feature. The above code and the follow code are equivalent in this case:

    Object.keys(window).forEach( function(key) {
      var type =  typeof window[key];
      console.log(key + " (" + type + ")");
    });
    

    (they are not equivalent if we use a one-liner arrow function, or the arrow function body uses this - again, well worth giving the explanation of arrow functions a quick read-through)

    This covers all enumerable properties, which is typically all you want. In the extremely unlikely case you need enumerable and non-enumerable properties, you use Object.getOwnProperties(...).