• Post category:JavaScript
  • Reading time:4 mins read

During the execution of our code, we need to redirect to another page. There are many ways to redirect a web page to another web page in JavaScript. So today we will explain how we can easily redirect a page using JavaScript.

Mostly all methods which use for web page redirection are related to the window.location object, which is a property of the Window object. (For more details about Window object checkout here).

Two ways to manage the redirection of web page

  1. Javascript URL redirection
  2. Using location object methods

1. Javascript URL redirection

Using window.location and window.location.href we can redirect to another web page. window.location is an object that holds the information about the current location of the document and href is property of window.location, window.location.href is full url of current page. Both works the same but differences in their usage.

window.location = "https://www.codepremix.com/"
window.location.href = "https://www.codepremix.com/";

If you want to redirect to internal website page use:

window.location.href = "/category/javascript";

2. Using location object methods

Let’s start with another way to redirect to another web page using window location object.

1. reload()

reload() method used to refresh or reload the current page.

window.location.reload();
2. replace()

replace() is the method of window.location object, it will replace the current document with a new one. It rewrites the current page in history, which may affect behaviour of back button.

window.location.replace('https://www.codepremix.com/');
3. assign()

assign() method loads a new document in the browser window. This method different than replace() method because it rewrites the current page in history so when we click the back button, we go back to last visited page.

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

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!

Leave a Reply