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.

Leave a Comment