When coding in JavaScript, how do you programmatically redirect to a new page or URL?

JavaScript has a built-in way to do this using the Location API interface, which represents the location (URL) of the current web page you're located on. The global Window interface has access to the Location object that can be used via window.location.

Using that interface, you can use the replace() method like this:

    
      window.location.replace("DESTINATION_URL")
    
  

The replace() method will replace the current resource with the one at the provided URL.

If the new URL assignment can't occur because of a security violation, a DOMEXCEPTION of the SECURITY_ERROR type will be thrown. And if the new URL is invalid, a DOMEXCEPTION of the SYNTAX_ERROR type will be thrown.

As an example, here is how you'd redirect to the Google homepage:

    
      window.location.replace("https://www.google.com")
    
  

To quickly test this, open the developer tools in your favorite browser and execute the above code in the JavaScript console. The page should redirect to the Google homepage.

You'll notice that you can't use the browser's back button to navigate to the original page.

For more information on the browser support for the location.replace() method, see its MDN web docs page.

Thanks for reading and happy coding!