Understand the window Object in JavaScript

 Introduction

In this article we will understand the “window” object in the JavaScript language. In JavaScript most of the objects are created on top of the window object. Actually the “window” object represents the browser window and many properties of it. In this article we will understand a few of them with a practical approach.

The window object is supported by all browsers. It represents the browser's window.
 
All global JavaScript objects, functions, and variables automatically become members of the window object.
 
Global variables are properties of the window object.
 
Even the document object (of the HTML DOM) is a property of the the window object.
 
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head runat="server">  
  4. </head>  
  5. <body>  
  6.      <form id="form1" runat="server">  
  7.         <script>  
  8.             alert(window.document.write("writtten in window"));  
  9.         </script>  
  10.           
  11.     </form>  
  12.   
  13. </body>  
  14. </html>  
 

Now let us attach a variable to the window object.

  1.  <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head runat="server">  
  4. </head>  
  5. <body>  
  6.      <form id="form1" runat="server">  
  7.    
  8.         <script>  
  9.             var name = "sagar";  
  10.    
  11.             function xyz() {  
  12.                 alert("value of name is:- " + window.name);  
  13.             }  
  14.               
  15.    
  16.         </script>  
  17.         <input type="button" value="value" name="value" onclick="xyz()" />  
  18.     </form>  
  19.   
  20. </body>  
  21. </html>  
 
 
 
When we navigate from page to page in a web application, all the history is stored in the history object. We can get the length of the history object created on top of the “window” object, as shown in the following:
  1.  <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head runat="server">  
  4. </head>  
  5. <body>  
  6.     <form id="form1" runat="server">  
  7.          <script>  
  8.             alert("Length of history:- " + window.history.length);  
  9.         </script>  
  10.    
  11.     </form>  
  12.   
  13.   
  14. </body>  
  15. </html>  
 
 
 
Summary

In this article we learned about the window object in JavaScript. In a future article we will learn more basic concepts of JavaScript.
 
Reference

Up Next
    Ebook Download
    View all
    Learn
    View all