JS Location Object
In this page:
What Is the Location Object?
window.location represents the URL of the currently loaded page and provides both read access to its parts and methods to navigate elsewhere. It's available as either window.location or the shorter location.
Example: What Is the Location Object?
console.log(location.href); // full URL of the current page
Reading URL Parts
location.href gives the full URL as one string, while location.hostname, location.pathname, and location.search break it into the domain, the path after the domain, and the query string respectively. Parsing these individually is far more reliable than manually slicing the href string.
Example: Reading URL Parts
console.log(location.hostname);
console.log(location.pathname);
console.log(location.search);
Navigating Programmatically
Setting location.href = 'newpage.html' or calling location.assign('newpage.html') both navigate the browser to a new URL and add the move to browser history, while location.replace() navigates without leaving the current page in history.
Example: Navigating Programmatically
// location.href = "newpage.html"; // navigates, adds to history
// location.assign("newpage.html"); // same as above
// location.replace("newpage.html"); // navigates, no history entry
console.log(location.href);
Reloading the Page
location.reload() reloads the current page exactly as a manual refresh would, re-fetching all resources; there's no built-in argument to force a hard cache-bypassing reload from JavaScript alone anymore in modern browsers.
Example: Reloading the Page
// location.reload(); // re-fetches all resources, like a manual refresh
console.log("Current page:", location.href);
Reading Query Parameters
location.search returns the raw query string starting with '?', which combined with the URLSearchParams API lets you extract individual parameter values cleanly instead of hand-parsing the string with split() and indexOf().
Example: Reading Query Parameters
const params = new URLSearchParams(location.search);
console.log(params.get("id")); // reads a query parameter cleanly
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: