The Window Object
The Global Browser Object
In JavaScript, when it runs in a web browser, the Window Object is the absolute king. It represents the browser's window and acts as the global object for all JavaScript code running inside that tab.
Everything you write in global JavaScript—variables, functions, and even built-in methods like console.log—technically belongs to the window object!
Global Variables and the Window
When you declare a global variable using var, it attaches itself directly to the window object (which is one reason we avoid var!).
var myName = "Himanshu";
console.log(window.myName); // "Himanshu"
(Note: Variables declared with let and const do NOT attach to the window object).
Built-in Window Methods
You've likely been using Window methods without even realizing it, because you are allowed to skip typing window. in front of them!
1. Alerts, Prompts, and Confirms
// These are technically window.alert(), window.prompt(), etc.
alert("Welcome to Himubey Learn!");
let confirmDelete = confirm("Are you sure you want to delete this?");
2. Timers
Functions like setTimeout and setInterval belong to the window object.
window.setTimeout(() => {
console.log("This prints after 2 seconds!");
}, 2000);
3. Window Properties You can check properties of the user's browser window, like its height and width:
console.log(window.innerHeight); // Viewport height in pixels
console.log(window.innerWidth); // Viewport width in pixels
💡 Himanshu's Tip:
When building React or Next.js applications, remember that the window object only exists in the browser! If you try to access window.innerWidth during Server-Side Rendering (SSR) in Next.js, your app will crash. Always wrap window code inside a useEffect hook!
Interview Questions
- Is the
windowobject part of JavaScript itself, or is it provided by the browser? - What happens to variables declared with
letin the global scope regarding thewindowobject? - Why is it dangerous to attach too many variables to the global
windowobject?