What is the difference between location.replace, location.assign and location.href ?






In this tutorial, we are going to learn the difference between window.location.replace(), window.location.assign() and window.location.href. 

Let's first learn what does location.replace(), location.assign() and location.href does.

All three are used to redirect from one page to another. But still, there is some difference between them. Let us find out when to use which method.


window.location.href

window.location.href is a property that helps you get the current URL location of the browser. When we change the value of the window.location.href we get redirected to another page.

window.location.href,  keeps the current document in history. 

Use location.href if you want to load a new document, and the option to navigate back to the original document.


// Find current URL of browser.
console.log(window.location.href)

// Redirect to URL assigned while keeping the document history.
window.location.href = "https://www.geekstutorialpoint.com"


window.location.assign()

window.location.assign is a method that accepts URL as a parameter. When executed, window.location.assign(URL) redirects to the url specified while keeping the document history.

Syntax
window.location.assign("https://www.geekstutorialpoint.com")



window.location.replace()

window.location.replace is also a method that accepts URL as a parameter. When executed, window.location.replace(URL) redirect to the url specified but there is a catch.

In this method, the currently active URL of the browser in the document history is replaced with the URL specified. Therefore, when we click on the back button of the browser we do not go back to the previous page from where the method is executed. So, we can say that it doesn't maintain document history.

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


Summary

Let us conclude the difference with the help of an example - 

Suppose, we are on the "https://www.google.com" page in our browser (default first page), and then we redirect to "https://www.geekstutorialpoint.com" using the above methods respectively.

Now let us check, what will happen when we click on the back button of the browser.

location.href - We go back to the google page.
location.assign - We go back to the google page.
location.replace - Back button is disabled because document history has only 1 page.




Thanks for reading, please feel free to contact.

Post a Comment

0 Comments