In JavaScript, the window and document objects are both part of the Browser Object Model (BOM) and Document Object Model (DOM), respectively. Here's the key difference:
| Feature | window |
document |
|---|---|---|
| Definition | Represents the browser window/tab itself. | Represents the web page loaded in the window. |
| Origin | Part of BOM (Browser Object Model). | Part of DOM (Document Object Model). |
| Example usage | window.alert("Hello") |
document.getElementById("title") |
| Role | Global object containing browser features like location, history, setTimeout. |
Represents the HTML structure and content (DOM tree). |
| Accessing HTML | Cannot access specific HTML elements directly. | Used to access and manipulate HTML elements. |
| Implicit | Global scope variables/methods are properties of window (e.g., alert, console). |
Must explicitly access document to reach DOM. |
Code Example:
console.log(window.innerWidth); // width of browser window
console.log(document.title); // title of the HTML document
In summary:
windowis the browser environment.documentis the webpage content inside that environment.