How do you redirect to a new page in JavaScript?

JavaScript

The short answer

The most common way is window.location.href = '/new-page'. You can also use window.location.replace() which replaces the current history entry (the user cannot go back). In React, use the router's navigation methods instead of manipulating window.location directly.

Common methods

// Navigate to a new page (adds to history — user can go back)
window.location.href = 'https://example.com';
// Replace current page (cannot go back)
window.location.replace('https://example.com');
// Reload the current page
window.location.reload();
// Navigate using assign (same as setting href)
window.location.assign('https://example.com');

href vs replace

  • window.location.href — adds a new entry to history. The user can click back to return.
  • window.location.replace() — replaces the current entry. The user cannot go back. Use this for redirects after login or form submission.

In React

Do not use window.location in React — it causes a full page reload. Use the router instead:

// React Router
import { useNavigate } from 'react-router-dom';
function LoginPage() {
const navigate = useNavigate();
const handleLogin = () => {
// ... login logic
navigate('/dashboard');
// or replace (no back button)
navigate('/dashboard', { replace: true });
};
}

Interview Tip

Show window.location.href and window.location.replace() and explain when to use each. In a React context, mention useNavigate from React Router. Keep it simple — this is a quick knowledge question.

Why interviewers ask this

This tests basic JavaScript and browser API knowledge. It also reveals whether you know the difference between adding to history and replacing it, which matters for user experience.