JavaScript Window Object

The window object in JavaScript represents the browser's window or a frame that displays the webpage. It is the global object for JavaScript in the browser, meaning that all global variables and functions are properties of window.

Key Features of the Window Object:

Accessing Properties on the Window Object:

You can access the properties and methods on the window object directly:

Example


console.log(window.innerWidth);   // Width of the window's content area
console.log(window.innerHeight);  // Height of the window's content area
                    

Output

Width and height of the window's content area in the console

Displaying Alerts, Confirmations, and Prompts:

The window object provides methods to display messages to users:

Example


window.alert("This is an alert box!");
let isConfirmed = window.confirm("Are you sure?");
let userName = window.prompt("Enter your name:");
                        
console.log(isConfirmed);   // true or false based on user input
console.log(userName);      // User's input
                    

Output

Alert box, confirm dialog, and prompt box for user input

Opening a New Browser Window:

You can open a new browser window using the window.open() method:

Example


let newWindow = window.open("https://www.example.com", "_blank", "width=500,height=500");
        
// To close the new window
newWindow.close();
                    

Output

Opens a new browser window with specified dimensions

Setting Timers with setTimeout() and setInterval():

The window object has methods to execute code after a delay or at regular intervals:

Example


// Delayed execution
window.setTimeout(() => {
    console.log("This message appears after 2 seconds.");
}, 2000);

// Repeated execution
let intervalId = window.setInterval(() => {
    console.log("This message appears every 1 second.");
}, 1000);

// To stop the interval
window.clearInterval(intervalId);

                                         

Output

Messages in the console with specified delay and interval

When to Use the Window Object:

The window object is essential for interacting with the browser environment, controlling pop-ups, setting timers, and accessing other browser objects.