JS Window
JavaScript window Object: Browser Viewport and Global APIs
The window object represents the current browser tab and serves as the global scope for Browser Object Model (BOM) APIs. Everything from document, location, localStorage, and fetch() to viewport dimensions lives on window.
Measuring Viewport Dimensions and Scrolling
Front-end layouts often inspect viewport width or scroll position through window:
window.innerWidth/window.innerHeight: Width and height of the visible browser viewport in CSS pixels (including scrollbars).window.scrollX/window.scrollY: How many pixels the document is currently scrolled horizontally or vertically.window.scrollTo({ top: 0, behavior: "smooth" }): Smoothly scrolls the page back to the top.window.matchMedia("(max-width: 768px)"): Tests CSS media queries in JavaScript and listens for breakpoint changes cleanly.
Practical Window and localStorage Example
Avoid calling window.open() unprompted—modern browsers block popups unless triggered directly inside a user click handler.
console.log("Viewport size:", window.innerWidth, "x", window.innerHeight);
console.log("Current scrollY:", window.scrollY);
const prefersDark = window.matchMedia?.("(prefers-color-scheme: dark)")?.matches;
console.log("User prefers dark mode:", Boolean(prefersDark));
// Safe feature check for globalThis (works in Browser + Node.js)
console.log("Same global object:", globalThis === window);
Common Mistakes to Avoid
- Assuming
windowexists during Server-Side Rendering (SSR): Frameworks like Next.js run components on Node.js first wherewindowisundefined. Guard browser-only reads withtypeof window !== "undefined"or run them insideuseEffect(). - Polling
resizeevents without debouncing: Listening towindow.addEventListener("resize", ...)fires dozens of times during a drag; preferwindow.matchMedia(...).addEventListener("change", ...)for responsive breakpoints. - Adding custom properties directly onto
window: Attachingwindow.myState = ...risks colliding with third-party scripts or future browser globals.
Frequently Asked Questions
What is globalThis and how does it relate to window?
globalThis is the standard cross-platform reference to the global object—it equals window in browsers, self in Web Workers, and global in Node.js.
Why do var variables attach to window while let and const do not?
Top-level var in non-module scripts adds properties onto window, whereas let, const, and ES modules stay isolated outside window properties.
How do I detect when a user leaves or returns to the browser tab?
Listen to the "visibilitychange" event on document and check document.visibilityState === "visible".
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.