window.location versus just location
Asked Answered
R

9

89

Across the web, I see a vast number of JavaScript programmers writing window.location instead of just location. I was curious if anyone could offer an explanation as to why. window is the global object, and therefore it is unnecessary to include -- isn't it? I mean, you don't see people write window.Math.floor or new window.Date(), so I'm curious as to why it would be specified with location.

I understand that location is considered to be a "property" of the window you're in, which I suppose makes some sense. But even so, I don't see any reason to specify the global object; it's not possible to overwrite location in the first place, not without redirecting the page.

So, is this just a quirk that has been used for so long that it's become integrated with how we write JavaScript, or is there some tangible reason to do things this way? I checked Google, but alas, I came up with nothing...

Radio answered 17/1, 2011 at 0:21 Comment(0)
K
101

I always use window.location in my code for two principal reasons:

  1. It's a good habit to avoid global variables whenever possible. Using the window. prefix reminds me that the variable is global and that others aren't.
  2. The nature of Javascript's scoping allows you to override variables set higher up the scope tree. This means that you could have set var location somewhere in a containing scope (it's not an unlikely word to use as a variable name) and you'd be working on that instead.

For me, clarity of purpose when coding is very important as it helps me avoid writing bugs and then helps me find them when I do.

Karame answered 17/1, 2011 at 0:34 Comment(2)
I also imagine that telling JS where to find the variable instead of making it loop over the scope chain up to global scope can be a faster approach.Limbic
@Limbic No, actually, because JS also has to loop through the scope chain in order to determine what window is.Karame
L
18

Partly for safety in case someone defines a location variable somewhere in the scope chain. the window.location makes it an explicit reference to the property of window.

Example: http://jsfiddle.net/dr6KH/

(function() {
    var location = 'new value'; // creating a local variable called "location"

    (function() {
        alert(location);  // alerts "new value"

        alert(window.location);  // alerts the toString value of window.location
    })();

})();
Layamon answered 17/1, 2011 at 0:30 Comment(0)
E
14

There's a big difference between window.location and the native Math and Date objects, which is that Math and Date are native JavaScript objects that are specified to exist as properties of the global object, while window.location is a property of the window host object (a host object is an object representing some aspect of the environment, provided by the environment, and is not subject to the same rules as native JavaScript objects. Other host objects include document and any DOM element).

window in browsers serves two purposes: first, acting as the (well-specified) ECMAScript global object, and second, acting as a host object providing information about the browser environment. For uses of window in its host object capacity, I prefer to be explicit and provide the window. prefix: the fact that location works without it is just a coincidence that comes from window's schizophrenic nature. Also, as pointed out by other answers, this also has the advantage of protecting you in the case when another location variable exists in the current context.

One good reason for not prefixing Date or Math with window. is that doing so creates code that does not work in a non-browser environment. Other environments generally do not provide window as an alias for the global object.

Echo answered 17/1, 2011 at 10:22 Comment(0)
U
6

Part of coding is clarity. Unlike Math or Date, location is conceptually a property of the window, so the code becomes more clear to include it. The "window." prefix should ideally be removed for minification.

You are probably correct that a lot of the reason is historical. Javascript has an extensive history of copying and pasting.

Uam answered 17/1, 2011 at 0:26 Comment(1)
That's what I figured, but there are so many people that do it; pretty much every source I see uses window.location. The only "versus" pages I could find discuss window.location vs location.href, which didn't help either.Radio
L
5

It is not always just a matter of style - I was trying to load social media buttons asynchronously after the window's load event by appending script elements to a fragment, and then appending that fragment to the document. Twitter's widgets.js uses location.href in several places and was causing the following error in IE 8/9: Unexpected call to method or property access. I haven't figured out why, but this only happens when visiting the page via a link from another page. If you just append the script element to the head or use window.location.href, this doesn't occur, so it appears to be some weirdness with IE 8/9 and createDocumentFragment().

Example:

<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.stackoverflow.com">Tweet</a>
<script>
(function (d, t) {
    var head = document.getElementsByTagName('head')[0];
    var frag = d.createDocumentFragment();
    var s = d.createElement(t);
    s.async = true;
    s.src = 'http://platform.twitter.com/widgets.js';
    frag.appendChild(s);
    head.appendChild(frag);
} (document, 'script'));
</script>
Longhair answered 18/12, 2012 at 19:48 Comment(0)
J
4

The window object is the default working namespace, so location will be equal to window.location.

I think that using location is a bit ambiguous, use window.location for clarity.

Jetpropelled answered 17/1, 2011 at 0:27 Comment(2)
I voted for this answer (and almost none of the others) because, imagine this silly example: function f() { var location = "home"; /* later on */ location = "http://google.com" } cryBrainard
@Brainard By that logic you should write window.document every time. I doubt anybody's doing that.Protomorphic
R
2

It's just a matter of style.

Conceptually, location is a property of the window (the window is at a location), unlike Math or Date.

Refresher answered 17/1, 2011 at 0:23 Comment(0)
C
1

location is a property of the window object, so you can get it by requesting window.location. But if you don't specify an object, JavaScript assumes you want the window object. So just requesting location is the same as requesting window.location.

Coagulant answered 17/1, 2011 at 0:27 Comment(0)
C
0

They are actually identical. Technically, the "window" object IS the same thing as the root scope for Javascript variables.

Caravan answered 17/1, 2011 at 0:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.