Understanding URL location .host, .hostname, and location.href in JavaScript
When working with client-side JavaScript in web development, we often need to access or manipulate the URL of the current page. The window.location object provides a rich set of properties to help with this — but knowing when to use location.host, location.hostname, and location.href can save you from confusion or bugs.
Let’s break down the differences with real examples and use cases. 👇
📌 What is a Root URL?
The root URL is the starting point of your website — the top-most level of the domain, with no additional path or parameters.
👉 It’s like the front door of your digital house.
✅ Example:
If your full page URL is:
https://www.example.com/products/item1
Then your root URL is:
https://www.example.com/
That’s the base of everything.
🌐 location.hostname
✅ What it is:
location.hostname returns just the domain (hostname) part of the URL, without the port.
🧪 Example:
console.log(location.hostname);
// Output: "www.example.com"
🧱 location.host
✅ What it is:
location.host returns the hostname + port number, if a port is specified.
🧪 Example:
console.log(location.host);
// Output: "www.example.com:8080"
🔍 location.href
✅ What it is:
location.href gives you the entire URL of the current page as a string.
🧪 Example:
console.log(location.href);
// Output: "https://www.example.com:8080/path/page.html?query=123#section"
Difference : location.href = "/newpage"; and location.href = "newpage";
📌 location.href = "/newpage";
✅ What it does:
This is a root-relative URL.
📖 Meaning:
It navigates to /newpage starting from the root of the domain, no matter where the current page is located.
🧪 Example:
Current URL: https://example.com/products/item1
location.href = "/newpage";
➡️ Redirects to: https://example.com/newpage
✅ Always starts from the domain root (/).
📌 location.href = "newpage";
✅ What it does:
This is a relative URL.
📖 Meaning:
It navigates relative to the current path, based on where you are in the directory structure.
🧪 Example:
Current URL: https://example.com/products/item1
location.href = "newpage";
➡️ Redirects to: https://example.com/products/item1/newpage
🔁 It appends to the current directory path — which can lead to unexpected results if you're not careful.
💡 Final Tip
If you're ever unsure, remember: