📌 Introduction
In JavaScript, the window object is the global object in the browser environment. It represents the browser's window and provides access to many properties, methods, and events that let you interact with the browser. Essentially, everything in the global scope (like variables and functions) becomes a property of window.
🔑 Key Features of window
- Represents the browser window or tab.
- Acts as the global object in client-side JavaScript.
- Provides APIs for navigation, dialogs, storage, timers, and more.
- Contains the document object (for DOM manipulation).
🧩 Common Properties of window
| Property | Description |
|---|---|
| window.document | Represents the DOM of the page. |
| window.location | Gives information about the current URL and allows navigation. |
| window.navigator | Provides information about the browser and device. |
| window.history | Allows navigation through the session history. |
| window.localStorage | Stores data persistently in the browser. |
⚙️ Common Methods of window
- alert("Hello!") → Shows a popup alert box.
- confirm("Are you sure?") → Displays OK/Cancel dialog.
- prompt("Enter your name") → Accepts user input.
- setTimeout() → Runs code after a delay.
- setInterval() → Runs code repeatedly at intervals.
- open() → Opens a new browser window or tab.
💻 Code Examples
Basic Alert Example
window.alert("Welcome to JavaScript!");Using setTimeout
window.setTimeout(() => {
console.log("This runs after 2 seconds!");
}, 2000);Accessing Location
console.log(window.location.href);
// Example output: "https://example.com/page"🧠 Global Scope and window
Any variable or function declared with var at the top level becomes a property ofwindow. However, let and const do not attach to window.
Global Scope Example
var name = "Sathish";
console.log(window.name); // "Sathish"
let age = 25;
console.log(window.age); // undefinedNote
🌟 Conclusion
The window object is the backbone of client-side JavaScript in browsers. It not only controls the browser window but also provides essential APIs for interacting with the user, managing data, and navigating pages. Mastering window is a must for every web developer. 🚀
Learn more on MDN