Just define your variable in the same area in which you define your functions that rely on it. If your functions are in global scope, then your variable should be.
If you are developing a plugin or control or script that will be used on multiple pages, then yes, avoid global variables. If, on the other hand, you have a piece of data that depends on the page that you need in more than one place, the global variable is absolutely suitable.
Go criticize! Vote for me! And when you're done with this, check out some of my other answers, where I really advocate using tables in HTML! :-)
Sometimes you need to understand the rules so that you know when it is normal to break them.
Now, if you just realized that your functions are in global scope, and you want to change this, just wrap all your code in an anonymous function and immediately call it:
(function(){ var scopeLevelVariable = true; function scopeLevelFn(){ ... } window.globallyAvailableVariable = "foo"; window.globallyAvailableFunction = function(){ ... }; })();
source share