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

PropertyDescriptionExample Output
location.hrefThe full URL"https://example.com:8080/page?user=123#top"
location.protocolProtocol used"https:"
location.hostHostname + port"example.com:8080"
location.hostnameDomain name"example.com"
location.portPort number"8080"
location.pathnamePath of the URL"/page"
location.searchQuery string"?user=123"
location.hashAnchor/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