The Window Object

The window object is the global object in browsers that represents the browser's window. It provides access to the browser environment, allowing you to control and interact with the entire browser window and its features.

Illustration of The Window Object
Illustration of The Window Object

💡 Key Concept

All global JavaScript objects, functions, and variables automatically become members of the window object.

Core Characteristics of window

  • Represents the browser window or frame containing the script.
  • Global scope object — all global variables and functions are its properties.
  • Provides methods to manipulate the browser, access the document, and control timing events.

Commonly Used window Properties

Important Window Properties
PropertyDescription
window.documentAccesses the DOM (Document Object Model) of the current page.
window.locationProvides info about and allows manipulation of the current URL.
window.innerWidthWidth of the content area of the browser window.
window.innerHeightHeight of the content area of the browser window.
window.navigatorInformation about the browser and operating system.

Commonly Used window Methods

Important Window Methods
MethodPurpose
alert(message)Shows an alert dialog with a message.
confirm(question)Displays a dialog with OK/Cancel, returns user's choice.
prompt(text, default)Prompts user for input, returns the input value.
setTimeout(fn, delay)Executes function once after a delay (milliseconds).
setInterval(fn, delay)Executes function repeatedly at intervals (milliseconds).
clearTimeout(id)Cancels a timeout set by setTimeout.
clearInterval(id)Cancels an interval set by setInterval.

Window and Global Scope

Variables declared with var or functions declared globally become properties of window. For example:

📌 Deep Dive: Global Variable as Window Property

JAVASCRIPT
var name = "Alice";
console.log(window.name); // "Alice"

function greet() {
  alert("Hello!");
}
window.greet(); // calls greet function
Output
Alice (logged in console), alert popup with "Hello!"

⚠️ Important

Variables declared with let or const are NOT added as properties of the window object.

Controlling the Browser Window

  • window.open(url, name, specs): Opens a new browser window or tab.
  • window.close(): Closes the current window (only if opened by script).
  • window.scrollTo(x, y): Scrolls the window to specified coordinates.

Accessing window Object in Practice

Because window is the global object, you can omit it when accessing its properties or methods:

  • alert("Hi!") is equivalent to window.alert("Hi!")
  • location.href = "https://example.com" is equivalent to window.location.href = "https://example.com"

💡 Summary

The window object is your gateway to interacting with the browser environment, controlling windows, dialogs, timing, and more. Understanding it is essential for effective web programming.