← Back to JavaScript Course | Chapter 11: Browser Object Model | Lesson 3 of 6

JS Location Object

window.location is like the GPS display in a car: it tells you exactly where you are right now (the current URL) and lets you type in a new destination to travel to.

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?

javascript
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

javascript
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

javascript
// 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

javascript
// 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

javascript
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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.