Navigating with location
What you'll learn: How to programmatically change the page URL and control whether users can navigate back using JavaScript.
Now that you understand the window.location object and its properties, you can use it to actually navigate the browser to different pages—just like clicking a link, but with code.
Three Ways to Navigate
1. Setting location.href
The simplest approach is directly assigning a new URL to location.href:
// Navigate to a new page
window.location.href = 'https://example.com/dashboard';
This creates a new history entry, so the back button will work.
2. Using location.assign()
This method does the same thing as setting href, but more explicitly:
location.assign('https://example.com/dashboard');
Think of this as: "Assign a new destination and add it to the travel log."
3. Using location.replace()
This navigates without creating a history entry—the current page is replaced:
location.replace('https://example.com/dashboard');
The user cannot click back to the previous page. Think of this as: "Burn the bridge behind you—there's no going back."
When to Use Each
hreforassign(): Normal navigation where users should be able to return (after form submission, following a flow)replace(): After login redirects, fixing incorrect URLs, or preventing users from returning to invalid states
// After successful login, prevent back-navigation to login page
location.replace('/dashboard');
Key Takeaway: Use location.href or assign() for normal navigation with history, and replace() when you need to navigate without letting users go back.