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

JavascriptWindowLocation

Javascript Problem Overview


Is there a difference between these two lines?

var url = "http://www.google.com/";
window.location = url;
window.location.replace(url);

Javascript Solutions


Solution 1 - Javascript

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;

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAaron DigullaView Question on Stackoverflow
Solution 1 - JavascriptcletusView Answer on Stackoverflow
Solution 2 - JavascriptLpc_darkView Answer on Stackoverflow
Solution 3 - JavascriptStas SorokinView Answer on Stackoverflow