iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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

PropertyWhat it gives
window.innerWidth / innerHeightViewport size including scrollbars.
window.outerWidth / outerHeightWhole browser window.
window.scrollX / scrollYCurrent scroll offset.
window.documentThe page document.
window.locationThe current URL.
window.historyNavigation history.
window.navigatorBrowser/device info.
window.localStorage / sessionStorageWeb Storage.
window.cryptoWeb Crypto API.

Methods worth knowing

MethodPurpose
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';

Test yourself

Q1. The universal global across browsers, Node, and Workers is…
Q2. Viewport pixel width is…
Q3. Schedule before next paint with…

Discussion

Loading…