Is there a difference between these two lines?
var url = "http://www.google.com/";
window.location = url;
window.location.replace(url);
Is there a difference between these two lines?
var url = "http://www.google.com/";
window.location = url;
window.location.replace(url);
Is there a difference between these two lines?
window.location = "http://www.google.com/";
window.location.replace("http://www.google.com/");
Yes.
First, you want to know that:
window.location = "https://stackoverflow.com" is an alias of window.location.href = "https://stackoverflow.com" thus has the same functionality.
window.location VS window.location.replacewindow.location:
Here, I am addressing window.location = "https://website.com" in its context as window.location.href = "https://website.com"
window.location.replace:
To answer the question:
Yes, there is a difference between our 2 subjects and mostly in the fact that window.location enables you to go back in the browser history while window.location.replace() doesn't let you go back in browser history, thus removing the previous URL record from the browser history.
Bonus: Which is faster?
When you are using this: window.location = "http://www.google.com/"; you are updating the href property directly, this is faster by performance than using window.location.replace("http://www.google.com/"); because updating a function is slower than updating a property directly.
window.locationwindow.location returns the Location object that looks like this inside:
console.log(window.location);
// This is how the Location object that returns from window.location looks like
{
"ancestorOrigins": {},
"href": "https://stackoverflow.com/",
"origin": "https://stackoverflow.com",
"protocol": "https:",
"host": "stackoverflow.com",
"hostname": "stackoverflow.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
}
The Location object also has the following methods (functions):
Location.assign()
Loads the resource at the URL provided in parameter.
Location.reload()
Reloads the current URL, like the Refresh button.
Location.toString()
Returns a String containing the whole URL. It is a synonym for Location.href, though, it can't be used to modify the value.