- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript window Object
JavaScript Storage & BOM
JavaScript window Object
windowrepresents the browser tab and is the top of the global scope.
Every global variable and function is technically a property of it.
You rarely write window. yourself, but it is always there.
Example
Example
javascript
console.log(typeof window);
console.log(typeof window.document);Both are object.
What window Provides
window.innerWidth and innerHeight - the visible area.
window.location - the current URL.
window.document - the page itself.
Syntax
Syntax
javascript
window.innerWidth;
window.location.href;The window. prefix can usually be left off.
Globals Live on window
A variable declared at the top level becomes a property of it.
Example
Example
javascript
var globalCount = 5;
console.log(window.globalCount);
console.log(window.globalCount === globalCount);Note this only applies to var, not let or const.
let and const Do Not Attach
This is a difference worth knowing.
Example
Example
javascript
let notGlobal = 10;
console.log(window.notGlobal);
console.log(notGlobal);The variable still exists, just not as a property of window.
The Viewport Size
Useful for responsive behaviour driven from JavaScript.
Example
Example
javascript
console.log(typeof window.innerWidth);
console.log(window.innerWidth > 0);This changes as the window is resized.
Reading the URL
window.location describes the current page.
Example
Example
javascript
console.log(typeof window.location.href);
console.log(typeof window.location.hostname);The next lesson covers location in more detail.
alert, confirm and prompt
These pause the page and show a native browser dialog.
They are rarely used in real applications, since they block everything.
Example
Example
javascript
console.log(typeof window.alert);
console.log(typeof window.confirm);
console.log(typeof window.prompt);All three exist, even though modern interfaces avoid them.
Complete Example
Complete Example
html
<!DOCTYPE html>
<html>
<head>
<title>JavaScript window Object</title>
</head>
<body>
<h1>The window Object</h1>
<p id="out"></p>
<script>
document.getElementById("out").innerHTML =
"Window width: " + window.innerWidth +
"<br>Window height: " + window.innerHeight +
"<br>Current page: " + window.location.href;
</script>
</body>
</html>Try It Yourself
Run the above example in the Try It Editor.
Try resizing:
Resize the preview and rerun to see the numbers change.
Important Points
windowrepresents the browser tab.- It is the top of the global scope.
varglobals attach to it;letandconstdo not.innerWidthandinnerHeightgive the viewport size.window.locationdescribes the current URL.
Conclusion
Almost everything global in a browser page hangs off window.
Knowing that explains where document, alert and the rest come from.
The prefix is usually invisible, but it is worth knowing it is there.
