What's the difference between window.location= and window.location.replace()?
Asked Answered
N

3

326

Is there a difference between these two lines?

var url = "http://www.google.com/";
window.location = url;
window.location.replace(url);
Nicotiana answered 8/12, 2009 at 9:40 Comment(2)
W
484

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;
Watersoak answered 8/12, 2009 at 9:41 Comment(8)
Why would window.location.href be favored over window.location?Theogony
Discussion here: #2383901Nice
Question - If I use window.location.replace(URL) where URL is exactly the same as the current one, can I expect it to refresh/reload or does it have the option of doing nothing?Endgame
The accepted answer says there is no favorite in this case.Adila
What's the difference between window.location.href = and window.location.assign(Cohort
@Cohort by using window.location.assign(), you can test your code easierCudweed
@MgsMRizqiFadhlurrahman how come it's easier to test code with location.assign?Cohort
@Cohort for example, if you're using jest, you can mock the location object and then you can just expect the assign() function to be called: expect(window.location.assign).toBeCalledWith('/something-here')Cudweed
R
13

TLDR;

use location.href or better use window.location.href;

However if you read this you will gain undeniable proof.

The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.

location = "#/mypath/otherside"
var sections = location.split('/')

This code is perfectly correct syntax-wise, logic wise, type-wise you know the only thing wrong with it?

it has location instead of location.href

what about this

var mystring = location = "#/some/spa/route"

what is the value of mystring? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?

This i can pretty much guess all browsers will handle the same.

var mystring = location.href = "#/some/spa/route"

What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?

This conversation is so much deeper than just the location object however. What this conversion is about what kind of programmer you want to be?

If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.

There will be more objects. There will be new syntax.

You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.

var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"

With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.

Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.

Do the things that you can consistently do.

+"2" <-- this right here parses the string to a number. should you use it? or should you use parseInt("2")?

what about var num =+"2"?

From what you have learn, from the minds of stackoverflow i am not too hopefully.

If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.

Let me show you how this pays off. Normally I place ; on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.

I wrote something similar to this in es6 and babel

var a = "hello world"
(async function(){
  //do work
})()

This code fail and took forever to figure out. For some reason what it saw was

var a = "hello world"(async function(){})()

hidden deep within the source code it was telling me "hello world" is not a function.

For more fun node doesn't show the source maps of transpiled code.

Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.

I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.

Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.

what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.

My last note to ponder upon.

Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.

You can use more things plugins, Libraries with out fear of interruption between the codes.

for the record. use

window.location.href

Rowel answered 4/1, 2016 at 8:5 Comment(7)
Long informative answer, passionately argued. But in arguing for use of window.location.href over window.location, you forgot the question was actually asking for the difference between these and window.location.replace()Asphaltite
Anytime I see TLDR I expect a SHORTER answer, not one that is 5x longer.Endgame
TLDR; use location.href or better use window.location.href; The TLDR is this line. The rest is the "answer".Manta
I don't think you make valid point by introduce uncommon use case. i.e. mystring = location.href = "#/some/spa/route". Besides, many language would allow (implicit) type cast in some way. At the end of day, javascript is a dynamic typed language, put type concepts on it and say it's not good makes no point afaict.Typographer
re your es6 example, I think a good editor should indent your code and you can find out there is something wrong pretty quickly. (besides that, this is IIFE, not really relevant to es6)Typographer
what if someone overwrite the location object. well, just like saying what if someone overwrite console or shadow window -- Now you have a bigger problem.Typographer
If a form processing page does a redirect, replace is better to prevent the back button from returning to the processing page.Scruple
C
5

Origins & a Solution

The Question

Is there a difference between these two lines?
window.location = "http://www.google.com/";
window.location.replace("http://www.google.com/");

Short Answer

Yes.

Background Facts

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.replace

window.location:

Here, I am addressing window.location = "https://website.com" in its context as window.location.href = "https://website.com"

  • The href property on the location object stores the URL of the current webpage.
  • On changing the href property, a user will be navigated to a new URL.
  • This adds an item to the history list
  • after moving to the next page, the user can click the "Back" button in the browser to return to this page.

window.location.replace:

  • The replace function is used to navigate to a new URL without adding a record to the history.
  • This function is overwriting the topmost entry and replaces it from the history stack.
  • By clicking the "Back" button, you will not be able to return to the last page you visited before the redirect after moving to the next page.

Conclusion:

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.

More about window.location

window.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.

Clumsy answered 28/1, 2022 at 0:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.