In JavaScript, window and document are both objects that provide access to different parts of the browser’s functionality. Here’s a detailed explanation of their differences:
window object
- Definition: The
windowobject represents the browser’s window or tab that contains the web page. It is the top-level object in the browser’s JavaScript environment. - Global Scope: All global variables and functions are properties of the
windowobject. For example,alert,setTimeout, andlocationare methods or properties of thewindowobject. - Key Properties and Methods:
window.alert(): Displays an alert box.window.setTimeout(): Executes a function after a specified delay.window.location: Provides access to the URL of the current page.window.localStorage: Provides access to local storage.window.innerWidthandwindow.innerHeight: Dimensions of the browser window.
- Example:
console.log(window.location.href); // Logs the current page URL
document object
- Definition: The
documentobject is a property of thewindowobject and represents the content of the web page (the DOM – Document Object Model). - Access to the DOM: The
documentobject is used to interact with and manipulate the structure and content of the webpage. - Key Properties and Methods:
document.getElementById(): Selects an element by its ID.document.querySelector(): Selects the first matching element using a CSS selector.document.createElement(): Creates a new HTML element.document.body: Represents the<body>element of the page.document.title: Gets or sets the title of the document.- Example:
document.getElementById("myDiv").innerText = "Hello, world!";
Summary of Differences
| Feature | window | document |
| Represents | Browser window/tab | Web page content (DOM) |
| Scope | Top-level object | Part of the window object |
| Usage | General browser-related actions | DOM manipulation |
| Examples | window.alert(), window.location | document.getElementById(), document.body |
Relationship Between Them
The document object is a property of the window object. You can access document as window.document, but typically, it’s just referenced as document for simplicity.
console.log(window.document === document); // true
