window.location versus just location window.location versus just location javascript javascript

window.location versus just location


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.


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    })();})();


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.