JavaScript article thumbnail image.

How do you programmatically navigate to a new page or URL when coding in JavaScript?

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.

Included in the Location interface is a href value, which represents a USVString containing the whole URL for a page.

This value can also be assigned a different and new URL:

window.location.href = ""

By setting a new value for location.href, the page will navigate to the new URL you provide.

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.

By navigating to a new page in this manner, the original page will stay in the session History. Therefore, users will be able to use the back button in their browser to return to the original page.

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

Thanks for reading and happy coding!

About the author

Hi, I'm Nick Major. I'm a software developer from Wisconsin, United States.

I create free and premium courses, have published hundreds of informational coding articles, and am currently a Frontend Software Engineer at RoundingWell.

You can read more about me here.

Picture of Nick Major.