JavaScript — Location
The location object
console.log(location.href);
// https://example.com/products?page=2#details
Every URL piece has its own property:
| Property | Value for the URL above |
|---|---|
protocol | https: |
host | example.com |
hostname | example.com (port stripped if default) |
port | "" unless non-default |
pathname | /products |
search | ?page=2 (includes the ?) |
hash | #details |
origin | https://example.com |
Navigating
location.href = "https://example.com"; // go there (history entry kept)
location.assign("https://example.com"); // same thing, explicit
location.replace("https://example.com"); // NO back-entry to current page
location.reload(); // refresh
location.hash = "#about"; // in-page jump only
replace is ideal after logouts/redirects where Back should not return to a dead session page.
Reading query parameters properly
search includes the ?, so hand it straight to URLSearchParams:
const params = new URLSearchParams(location.search);
params.get("page"); // "2"
params.has("q"); // boolean
params.set("page", "3");
Building URLs safely
Never concatenate user input into URLs:
const url = new URL("https://example.com/search");
url.searchParams.set("q", "javascript & more"); // encoded automatically
url.href; // https://example.com/search?q=javascript+%26+more
Hash navigation
Setting hash jumps to matching-id elements without reload — the JS side of anchor links.
SPA note
Single-page apps avoid location.href per route (full reloads) and use the History API instead — next lesson.
Security: never redirect with untrusted values:
location.href = userInputenables open-redirect phishing. Validate destinations against an allowlist.
Mini Practice
- Log every location property for the current page.
- Read
?page=from the query string via URLSearchParams. - Change the hash; observe smooth/no-reload jump.
- Compare assign vs replace behavior with the Back button.
- Build a filtered search URL with URL + searchParams.
Next: history →
Related Topics
Frequently Asked Questions about Location
What is Location in JavaScript?
Location is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Location?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Location.
Why is Location important in JavaScript?
Location is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.