JavaScript Windows & Redirects
To understand redirects in JavaScript, you must first understand the BOM (Browser Object Model). While the DOM (Document Object Model) deals with the HTML contents of the page, the BOM allows JavaScript to "talk" to the browser itself.
The Window Object
The window object represents the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object. Even the Document Object Model (DOM) is a property of the window object.
Window Location
The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page. Since `window` is the global object, you can simply write `location` instead of `window.location`.
To redirect a user, you simply assign a new URL to the href property:window.location.href = "https://www.example.com";
Replace vs Assign
By default, setting `location.href` behaves exactly like location.assign(). It loads the new document and saves the previous document in the browser's history, meaning the user can click the "Back" button to return.
However, if you want to redirect a user and prevent them from returning to the original page (e.g., redirecting away from a login screen after successful authentication), you should use location.replace(). This removes the current URL from the document history.
View Full Transcript+
This section covers the deep specifics of the window object, handling cross-origin issues, popup blockers intercepting window.open(), and modern approaches to routing (like React Router pushing to the History API without doing a hard window reload). A hard redirect via location.href triggers a full page refresh, which is often undesirable in Single Page Applications (SPAs).
