Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

How do you redirect to a new page in JavaScript?

Topics
JAVASCRIPT
Edit on GitHub

TL;DR

To redirect to a new page in JavaScript, you can use the window.location object. The most common methods are window.location.href and window.location.replace(). For example:

// Using window.location.href
window.location.href = 'https://www.example.com';
// Using window.location.replace()
window.location.replace('https://www.example.com');

How do you redirect to a new page in JavaScript?

Using window.location.href

The window.location.href property is used to get or set the URL of the current page. When you set this property, the browser will navigate to the new URL, and it will create a new entry in the browser's history.

window.location.href = 'https://www.example.com';

Using window.location.replace()

The window.location.replace() method is similar to window.location.href, but it does not create a new entry in the browser's history. This means that the user cannot use the back button to return to the original page.

window.location.replace('https://www.example.com');

Using window.location.assign()

The window.location.assign() method works similarly to window.location.href and creates a new entry in the browser's history.

window.location.assign('https://www.example.com');

Using window.location.reload()

If you want to reload the current page, you can use the window.location.reload() method. This method can be useful if you want to refresh the page without changing the URL.

window.location.reload();

Using window.history.pushState()

For more advanced use cases, such as single-page applications (SPAs), you can use the window.history.pushState() method. This method allows you to change the URL without reloading the page.

window.history.pushState({}, '', '/new-page');

Further reading

Edit on GitHub