Window object vs Document object

JavaScript

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.

// These are all on the window object
window.alert('Hello');
window.setTimeout(() => {}, 1000);
window.innerWidth; // browser viewport width
window.location.href; // current URL
// You can skip "window." — it is implied
alert('Hello');
setTimeout(() => {}, 1000);

Common things on window:

  • window.location — the current URL
  • window.history — browser history navigation
  • window.localStorage / window.sessionStorage — storage
  • window.innerWidth / window.innerHeight — viewport dimensions
  • window.navigator — browser information
  • setTimeout, 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 elements
document.getElementById('header');
document.querySelector('.btn');
document.querySelectorAll('p');
// Creating elements
const div = document.createElement('div');
// Reading document info
document.title; // page title
document.URL; // current URL
document.cookie; // cookies

The relationship

window (global object)
├── document (the DOM)
├── location
├── history
├── navigator
├── localStorage
├── console
├── setTimeout
├── fetch
└── ... 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.