Redirect Page to Separate URL in JavaScript

- 1 minute read

There’s a view ways to go about redirecting the user to a different page in JavaScript, but the below method is my favorite:

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

The above example uses the window.location.assign method to simulate an HTTP redirect to https://example.com.

I prefer window.location.assign over window.location.replace, because the latter method resets the current tab’s history, thereby disabling the back button.

You can also set the value of window.location.href to your preferred target URL, which will simulate a link click:

window.location.href = `https://example.com`;

Link to this section Conclusion

Anyway, that’s how you redirect a page to a separate URL in JavaScript. Enjoy!