Location and Navigation
You'll learn how to read and change the current page's URL and navigate programmatically using window.location and window.history.
What Is window.location?
The window.location object represents the current URL of the page. Think of it like your browser's address bar—you can read where you are, and you can change it to go somewhere else. It's a powerful interface between your JavaScript code and the browser's navigation system.
Reading URL Information
// Get the full URL
console.log(window.location.href);
// → "https://example.com/page?id=123#top"
// Get individual parts
console.log(window.location.hostname); // → "example.com"
console.log(window.location.pathname); // → "/page"
console.log(window.location.search); // → "?id=123"
console.log(window.location.hash); // → "#top"
Navigating with location
// Navigate to a new page (adds to history)
window.location.href = "https://example.com/new-page";
// Reload the current page
window.location.reload();
// Replace current page (doesn't add to history)
window.location.replace("https://example.com/different-page");
Programmatic Navigation with history
The window.history object lets you move through the browser's history stack:
// Go back one page
window.history.back();
// Go forward one page
window.history.forward();
// Go back 2 pages
window.history.go(-2);
These methods mimic the browser's back and forward buttons, allowing you to create custom navigation controls.
Key Takeaway: Use window.location to inspect and modify the current URL, and window.history to navigate through the browser's history stack programmatically—essential tools for controlling page navigation in JavaScript.