Js Window in JavaScript
window Object in JavaScript
The window object represents the browser window and is the global object in the browser environment. It provides properties and methods to interact with the browser and the web page.
Key Points
Every global variable or function becomes a property or method of the
windowobject.You can access
windowproperties directly (without writingwindow.) because it's the global context.Provides access to browser features like dialogs, timers, location, history, and more.
Commonly Used window Properties & Methods
| Property / Method | Description | Example |
|---|---|---|
window.alert() | Shows an alert dialog | window.alert("Hello!") |
window.confirm() | Shows a confirmation dialog | window.confirm("Are you sure?") |
window.prompt() | Shows a prompt dialog | window.prompt("Enter your name") |
window.location | Access current URL and navigation | window.location.href = "https://example.com" |
window.history | Access browser history (back, forward) | window.history.back() |
window.setTimeout() | Calls a function after a delay (ms) | window.setTimeout(() => alert("Hi"), 1000) |
window.setInterval() | Calls a function repeatedly at intervals | window.setInterval(() => console.log("Tick"), 1000) |
window.document | Reference to the DOM document object | window.document.getElementById("myId") |
window.innerWidth | Width of the browser viewport | console.log(window.innerWidth) |
window.innerHeight | Height of the browser viewport | console.log(window.innerHeight) |
window.open() | Opens a new browser window or tab | window.open("https://example.com") |
window.close() | Closes the current window | window.close() |
Example Usage
// Show an alert dialogalert("Welcome to the site!");// Redirect to a new pagewindow.location.href = "https://openai.com";// Log window sizeconsole.log("Width: " + window.innerWidth);console.log("Height: " + window.innerHeight);// Use setTimeout to delay a messagesetTimeout(() => { alert("This appears after 3 seconds");}, 3000);Notes
windowis automatically the global scope in browsers, so you can omitwindow.when calling many of its functions.However, prefixing with
window.is sometimes useful for clarity.
If you want, I can show you examples of interacting with window events like resize or scroll!