The window object in Javascript represents the browser window that contains the javascript code.
It serves as the top-level or global object in a browser environment and encompasses various properties, methods, and events related to the browser window.
In a browser environment, the `window` object represents the global object. It means that `window` object properties and methods are accessible globally within the Javascript code while the code is running in the browser such as location, window size, event listeners and many.
Environment Information: It provides information about the browser environment, such as the size of the viewport, the URL of the current page, and the user's screen resolution.
Interacting with the Browser: Once a document is rendered in a browser it enables Javascript to interact with the browser, controlling aspects such as navigation `window.location`, handling events `window.addEventListener()`, and opening new windows on browsers using the `window.open()`.
Event Handler Functions: The `window` object allows developers to register event listeners for various browser events like `load`, `resize`, and `scroll`.
Storage Access: The `window` object also provides access to various storage mechanisms such as cookies `window.document.cookie`, session storage `window.sessionStorage` and local storage `window.localStorage`.
Timers and Intervals: The window provides build-in methods such as `setTimeout()` and `setInterval()` to execute code after a specified delay or at regular intervals and provide functions to `clearTimeout` and `clearInterval` by passing argument `id` return by set methods.
Variables and functions declared without the var, let, or const keyword become properties of the window object.
// Declare Global Variable var globalVar = "I'm a global variable declared"; // Calling Global Variable console.log(window.globalVar); // Output: I'm a global variable declared // Declare Global Method var globalMethod = function() { console.log("Global Method") // Output: Global Method } // Calling Global Method window.globalMethod()
The window object allows us to handle events globally:
// Declare the event handler function function handleWindowResize() { console.log('Window Screen Resized'); } // Add event listener for the 'resize' event on the window object window.addEventListener('resize', handleWindowResize); // After 2 seconds, remove the event listener setTimeout(() => { console.log("Removing Event Listener after 2 seconds"); window.removeEventListener('resize', handleWindowResize); }, 2000);
window.addEventListener(): Attaches an event handler to the window.
window.removeEventListener(): Removes an event handler.
Removing Event Listener after 2 seconds