Course contentsShow
← Web Development
Lesson 944 of 2,98217. URL and History ManagementFree lesson

The window.location Object

Read and manipulate the current page URL using window.location properties and methods.

The window.location Object

You'll learn how to read and change the current page's URL using the built-in window.location object.

What Is window.location?

While the URL constructor (from the previous lessons) lets you parse and manipulate URL strings, window.location is a live object that represents the actual URL of the current page in your browser. Think of it like the address bar itself—reading from it tells you where you are, and writing to it takes you somewhere new.

Reading the Current URL

The window.location object has properties similar to the URL object you've already seen:

console.log(window.location.href);      // Full URL
console.log(window.location.protocol);  // "https:"
console.log(window.location.host);      // "example.com:8080"
console.log(window.location.hostname);  // "example.com"
console.log(window.location.port);      // "8080"
console.log(window.location.pathname);  // "/path/page"
console.log(window.location.search);    // "?id=123"
console.log(window.location.hash);      // "#section"

Navigating by Changing Location

When you assign a new value to certain window.location properties, the browser navigates to that URL:

// Navigate to a completely new URL
window.location.href = "https://example.com";

// Change just the hash (no page reload)
window.location.hash = "#top";

// Navigate using assign()
window.location.assign("https://example.com/new-page");

You can even reload the current page with window.location.reload().

Key Takeaway: window.location is your JavaScript interface to the browser's address bar—read its properties to inspect the current URL, and modify them to navigate to new pages.