The window object represents the browser window containing the DOM document. In client-side JavaScript, window acts as the global execution context object (globalThis), exposing browser dimensions, scroll offsets, timers, and storage engines.
flowchart TD
Window["window (Global Execution Scope)"] --> DOMDoc["document (DOM Root)"]
Window --> BOMNav["navigator (Browser Specs)"]
Window --> BOMLoc["location (URL Routing)"]
Window --> BOMHist["history (Session Navigation)"]
Window --> Storage["localStorage / sessionStorage"]
Window --> Viewport["Viewport Specs: innerWidth, innerHeight"]
| Property | Type | Description |
|---|---|---|
window.innerWidth |
Number | Width of viewport layout area (including scrollbars) in pixels. |
window.innerHeight |
Number | Height of viewport layout area in pixels. |
window.scrollX / scrollY |
Number | Pixels document is currently scrolled horizontally / vertically. |
window.devicePixelRatio |
Number | Ratio of physical display pixels to CSS pixels (Retina display ratio). |
window.localStorage |
Storage | Persistent key-value storage engine. |
// Demonstrating Window properties, dimensions, and global scope behavior
// 1. Implicit Global Scope
window.appVersion = "3.2.0"; // Explicit global property assignment
console.log(`Global App Version: ${appVersion}`); // Accessible without window prefix
// 2. Inspecting Viewport Dimensions
console.log(`Viewport Width: ${window.innerWidth}px`);
console.log(`Viewport Height: ${window.innerHeight}px`);
console.log(`Device Pixel Ratio (Retina factor): ${window.devicePixelRatio}`);
// 3. Window Scroll Control
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: "smooth" // Smooth scrolling animation
});
}
// 4. Listening for Window Resize Events
window.addEventListener("resize", () => {
console.log(`Resized Viewport Dimensions: ${window.innerWidth} x ${window.innerHeight}`);
});
globalThis for Cross-Platform Compatibility: Use globalThis when writing code intended to run across both browser environments (window) and Node.js environments (global).resize and scroll events fire rapidly; always debounce handlers attached to window.onresize.var in the global scope becomes an attached property on window. Avoid var to keep window clean.What is the difference between window.innerWidth and window.screen.width?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.