window Object: Browser Viewport and Global APIsThe 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.
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.localStorage ExampleAvoid 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);
window exists during Server-Side Rendering (SSR): Frameworks like Next.js run components on Node.js first where window is undefined. Guard browser-only reads with typeof window !== "undefined" or run them inside useEffect().resize events without debouncing: Listening to window.addEventListener("resize", ...) fires dozens of times during a drag; prefer window.matchMedia(...).addEventListener("change", ...) for responsive breakpoints.window: Attaching window.myState = ... risks colliding with third-party scripts or future browser globals.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.
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.
Listen to the "visibilitychange" event on document and check document.visibilityState === "visible".
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.