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

ID : 10298

viewed : 21

Tags : javascriptwindowlocationjavascript

Top 5 Answer for javascript - What's the difference between window.location= and window.location.replace()?

vote vote

97

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; 
vote vote

81

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

vote vote

71

vote vote

61

For Linq to Sql queries, you may get this warning. The lambda's scope may outlive the method due to the fact that the query is often actualized after the method is out of scope. Depending on your situation, you may want to actualize the results (i.e. via .ToList()) within the method to allow for GC on the method's instance vars captured in the L2S lambda.

vote vote

57

You could always figure out with a reasons of R# suggestions just by clicking on the hints like shown below:

enter image description here

This hint will direct you here.


This inspection draws your attention to the fact that more closure values are being captured than is obviously visibly, which has an impact on the lifetime of these values.

Consider the following code:

using System;  public class Class1 {     private Action _someAction;      public void Method() {         var obj1 = new object();         var obj2 = new object();          _someAction += () => {             Console.WriteLine(obj1);             Console.WriteLine(obj2);         };          // "Implicitly captured closure: obj2"         _someAction += () => {             Console.WriteLine(obj1);         };     } } 

In the first closure, we see that both obj1 and obj2 are being explicitly captured; we can see this just by looking at the code. For the second closure, we can see that obj1 is being explicitly captured, but ReSharper is warning us that obj2 is being implicitly captured.

This is due to an implementation detail in the C# compiler. During compilation, closures are rewritten into classes with fields that hold the captured values, and methods that represent the closure itself. The C# compiler will only create one such private class per method, and if more than one closure is defined in a method, then this class will contain multiple methods, one for each closure, and it will also include all captured values from all closures.

If we look at the code that the compiler generates, it looks a little like this (some names have been cleaned up to ease reading):

public class Class1 {     [CompilerGenerated]     private sealed class <>c__DisplayClass1_0     {         public object obj1;         public object obj2;          internal void <Method>b__0()         {             Console.WriteLine(obj1);             Console.WriteLine(obj2);         }          internal void <Method>b__1()         {             Console.WriteLine(obj1);         }     }      private Action _someAction;      public void Method()     {         // Create the display class - just one class for both closures         var dc = new Class1.<>c__DisplayClass1_0();          // Capture the closure values as fields on the display class         dc.obj1 = new object();         dc.obj2 = new object();          // Add the display class methods as closure values         _someAction += new Action(dc.<Method>b__0);         _someAction += new Action(dc.<Method>b__1);     } } 

When the method runs, it creates the display class, which captures all values, for all closures. So even if a value isn't used in one of the closures, it will still be captured. This is the "implicit" capture that ReSharper is highlighting.

The implication of this inspection is that the implicitly captured closure value will not be garbage collected until the closure itself is garbage collected. The lifetime of this value is now tied to the lifetime of a closure that does not explicitly use the value. If the closure is long lived, this might have a negative effect on your code, especially if the captured value is very large.

Note that while this is an implementation detail of the compiler, it is consistent across versions and implementations such as Microsoft (pre and post Roslyn) or Mono's compiler. The implementation must work as described in order to correctly handle multiple closures capturing a value type. For example, if multiple closures capture an int, then they must capture the same instance, which can only happen with a single shared private nested class. The side effect of this is that the lifetime of all captured values is now the maximum lifetime of any closure that captures any of the values.

Top 3 video Explaining javascript - What's the difference between window.location= and window.location.replace()?

Related QUESTION?