learn2kode.in

What Is the JavaScript Window Object?

The Window Object is the top-level object in the Browser Object Model (BOM). It represents the browser window or tab that displays a web page.In JavaScript, the window object is created automatically by the browser. All global JavaScript objects, functions, and variables become properties of the window object.

The window object controls the browser itself.

Why Is the Window Object Important?

The Window Object allows you to:

Global Scope & Window Object

Any variable or function declared globally automatically becomes part of the window object.
var siteName = "Learn2Kode";

function showName() {
  console.log(siteName);
}

console.log(window.siteName); // Learn2Kode
window.showName();            // Calls function
window is optional when accessing global variables.

Commonly Used Window Object Properties

1. window.innerWidth & window.innerHeight
Get the browser’s viewport size.
console.log(window.innerWidth);
console.log(window.innerHeight);

2. window.location

Used to get or change the current page URL.
console.log(window.location.href);

// Redirect user
window.location.href = "https://learn2kode.in";

3. window.history

Used to navigate browser history.
window.history.back();    // Go back
window.history.forward(); // Go forward

4. window.screen

Provides screen information.
console.log(screen.width);
console.log(screen.height);

Window Object Methods

Alert, Confirm & Prompt

alert("Welcome to Learn2Kode!");

confirm("Are you sure?");

prompt("Enter your name:");
Method Purpose
alert() Show message
confirm() OK / Cancel dialog
prompt() Take user input

Open & Close Window

window.open("https://learn2kode.in", "_blank");

window.close();
Closing works only for windows opened by JavaScript.

Timers in Window Object

setTimeout()

Runs code once after a delay.
setTimeout(() => {
  console.log("Executed after 2 seconds");
}, 2000);

setInterval()

Runs code repeatedly.
setInterval(() => {
  console.log("Repeats every second");
}, 1000);

Window vs Document (Quick Understanding)

Feature Window Object Document Object
Controls Browser Web page
Scope Global Page-specific
Example window.alert() document.getElementById()

When to Use Window Object?

Use the Window Object when you need to:

Key Takeaways