Window object vs Document object
The 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.
1// These are all on the window object2window.alert('Hello');3window.setTimeout(() => {}, 1000);4window.innerWidth; // browser viewport width5window.location.href; // current URL67// You can skip "window." — it is implied8alert('Hello');9setTimeout(() => {}, 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.
1// Selecting elements2document.getElementById('header');3document.querySelector('.btn');4document.querySelectorAll('p');56// Creating elements7const div = document.createElement('div');89// Reading document info10document.title; // page title11document.URL; // current URL12document.cookie; // cookies
The relationship
1window (global object)2 ├── document (the DOM)3 ├── location4 ├── history5 ├── navigator6 ├── localStorage7 ├── console8 ├── setTimeout9 ├── fetch10 └── ... everything else
document 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.