What is the Location API?
window.location represents the current page's URL: you can read its parts (protocol, host, path, query, hash) and change it to navigate, reload or redirect.
Reading the URL
location.href: the full URL.location.origin: protocol + host + port.location.pathname:/products/42.location.search:?sort=price&page=2. Parse it withURLSearchParams.location.hash:#reviews.location.host,hostname,port,protocol.
Navigating
location.assign(url)orlocation.href = url: navigate and add a history entry.location.replace(url): navigate and replace the current entry, so Back does not return to it. Use it for redirects such as after login.location.reload(): reload the page.- Setting
location.hashjumps to an anchor without reloading and fireshashchange.
Location vs History API
Changing location (except the hash) loads a new page. The History API changes the URL without loading anything, for single-page apps.
Working with URLs
The URL class parses and builds URLs safely: new URL(path, location.origin), url.searchParams.set("page", "2"). Avoid concatenating query strings by hand; URLSearchParams handles encoding.
Security
Never redirect to a URL taken directly from user input or a query parameter (?next=...) without validating it: open redirects are used in phishing. Allow only same-origin or known destinations.
Code example
1console.log(location.origin, location.pathname);23// Parse and build URLs safely instead of string concatenation4const url = new URL("https://shop.example.com/products?category=books&sort=price#reviews");5console.log(url.hostname, url.pathname, url.hash); // shop.example.com /products #reviews67const params = url.searchParams;8console.log(params.get("category"), params.has("sort")); // books true9params.set("page", "2");10params.set("q", "café & tea"); // encoded for you11params.delete("sort");12console.log(url.search); // ?category=books&page=2&q=caf%C3%A9+%26+tea1314// Read the current page's query string15const current = new URLSearchParams(location.search);16console.log(Object.fromEntries(current)); // whatever params this page has1718// Validate redirect targets (prevent open redirects)19function safeRedirectTarget(next, fallback = "/") {20 try {21 const target = new URL(next, location.origin);22 return target.origin === location.origin ? target.pathname + target.search : fallback;23 } catch {24 return fallback;25 }26}27console.log(safeRedirectTarget("/dashboard?tab=2")); // /dashboard?tab=228console.log(safeRedirectTarget("https://evil.example/phish")); // /2930// Navigation (commented out so the example doesn't leave the page):31// location.assign("/login"); // adds a history entry32// location.replace("/login"); // replaces the current entry
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.