Mastering the location Object in JavaScript
📌 Introduction
The location object in JavaScript represents the current URL of the browser window. It is a property of the window object and provides useful methods and properties to read, manipulate, and reload URLs. 🌐
>>"With location, you control navigation and URL management directly from JavaScript."
🔑 Accessing location
Access location
console.log(window.location);
// or simply
console.log(location);Since location is part of the global window object, you can access it directly without prefixing window..
📜 Properties of location
| Property | Description | Example Output |
|---|---|---|
| location.href | The full URL | "https://example.com:8080/page?user=123#top" |
| location.protocol | Protocol used | "https:" |
| location.host | Hostname + port | "example.com:8080" |
| location.hostname | Domain name | "example.com" |
| location.port | Port number | "8080" |
| location.pathname | Path of the URL | "/page" |
| location.search | Query string | "?user=123" |
| location.hash | Anchor/fragment | "#top" |
⚙️ Common Methods of location
- location.assign(url) → Loads a new document at the given URL.
- location.replace(url) → Replaces current page (no back option).
- location.reload() → Reloads the current page.
💡 Example Usage
Redirecting to Another Page
location.href = "https://google.com";Reloading the Page
location.reload();Using assign()
location.assign("https://example.com");Using replace()
location.replace("https://example.com");🧠 Practical Use Cases
- Redirecting users after login/logout. 🔑
- Refreshing a page to get updated content.
- Reading query strings (location.search) for dynamic content.
- Building SPAs (Single Page Apps) with hash navigation (location.hash).
⚠️ Things to Remember
Note
- location.replace() prevents going back using the back button.
- Using location.reload() may cause form resubmission warnings.
- Always validate user input if using query strings from location.search.
🌟 Conclusion
The location object is a powerful interface for working with URLs in JavaScript. From simple redirects to reading query strings and hashes, mastering it is essential for building interactive and dynamic web apps. 🚀
Learn more on MDN