Window object vs Document object
JavaScriptThe short answer
The window object represents the browser window and is the global object in JavaScript. Everything — variables, functions, the DOM — lives inside it. The document object is a property of window that represents the HTML document loaded in the page. You use window for browser-level things (navigation, timers, screen size) and document for DOM manipulation.
The Window object
window is the top-level object. When you declare a global variable or function, it becomes a property of window.
// These are all on the window objectwindow.alert('Hello');window.setTimeout(() => {}, 1000);window.innerWidth; // browser viewport widthwindow.location.href; // current URL// You can skip "window." — it is impliedalert('Hello');setTimeout(() => {}, 1000);Common things on window:
window.location— the current URLwindow.history— browser history navigationwindow.localStorage/window.sessionStorage— storagewindow.innerWidth/window.innerHeight— viewport dimensionswindow.navigator— browser informationsetTimeout,setInterval,fetch,alert,console
The Document object
document is a property of window (window.document). It represents the HTML page and provides methods to access and modify DOM elements.
// Selecting elementsdocument.getElementById('header');document.querySelector('.btn');document.querySelectorAll('p');// Creating elementsconst div = document.createElement('div');// Reading document infodocument.title; // page titledocument.URL; // current URLdocument.cookie; // cookiesThe relationship
window (global object) ├── document (the DOM) ├── location ├── history ├── navigator ├── localStorage ├── console ├── setTimeout ├── fetch └── ... everything elsedocument lives inside window. window.document and document are the same thing.
Interview Tip
Keep it simple: window is the browser, document is the page. Use window for browser APIs (location, storage, timers) and document for DOM manipulation (selecting elements, creating elements, reading page content).
Why interviewers ask this
This tests basic web platform knowledge. Interviewers want to see if you understand the JavaScript runtime environment in the browser and how the global object relates to the DOM. It is a foundational concept that comes up when discussing scope, global variables, and DOM APIs.