JS Window
The window object is the global scope in browsers. Every top-level variable, every browser-only API, and every BOM (Browser Object Model) property hangs off it.
Notable properties
| Property | What it gives |
|---|---|
window.innerWidth / innerHeight | Viewport size including scrollbars. |
window.outerWidth / outerHeight | Whole browser window. |
window.scrollX / scrollY | Current scroll offset. |
window.document | The page document. |
window.location | The current URL. |
window.history | Navigation history. |
window.navigator | Browser/device info. |
window.localStorage / sessionStorage | Web Storage. |
window.crypto | Web Crypto API. |
Methods worth knowing
| Method | Purpose |
|---|---|
window.scrollTo({ top, behavior }) | Programmatic scroll. |
window.open(url, target, features) | New tab/window. |
window.close() | Close — only works on windows you opened. |
window.matchMedia("…") | Run media queries from JS. |
window.requestAnimationFrame(fn) | Schedule before next paint. |
window.requestIdleCallback(fn) | Run when the browser is idle. |
globalThis — the universal global
JS
// Same as `window` in browsers, `global` in Node, `self` in Workers
globalThis.MY_API_KEY = "…";
// Detect the runtime
if (typeof window !== "undefined") { /* browser */ }
if (typeof process !== "undefined") { /* Node */ }
if (typeof importScripts === "function") { /* Web Worker */ }
Tip: Avoid adding properties to
window — they become globals and clash easily. Use modules instead; each module has its own scope.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Window!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Use the cross-environment global reference.
.MY_API_KEY = 'xyz';
Ten-letter universal global.
Discussion
Loading…