The only way to not have a global variable is to use the var keyword in the scope of a function. Anything else is a global variable.
(function() {
var local = 5;
})();
It doesn't matter if the function is a literal or function definition, it has to be some type of function.
Global variable examples:
1:
var global = 5;
The above is not in a function scope, therefore global even if var is used.
2.
(function() {
global = 5;
})();
In the above, no var was used, so it becomes an implied global.
3.
function foo(){}
foo was not defined inside of another function or assigned to a object key so its globally accessible.
4.
(function() {
var local = global = 5;
})();
When doing multiple assignments with var, only the first variable becomes local... so global is a global variable and equates to 5.
5.
window.foo = 5;
Prefixing window. is an explicit way of defining a global variable in the context of a browser.
6.
this.x = 5;
By default in browsers, this points to the DOMWindow unless you're in a method that's attached to an object which is not window. It's the same as #5. Note that if you use a method like XMLHttpRequest, the context is of the window.
7.
with ( window ) { name = 'john'; }
If you use the with statement and you dont reference an object that already has a property, a global variable is defined.
Declare the variable outwith of any of your functions, that way it becomes a global variable.
Here's an example of a global variable. The first function uses the global but the second function uses a local variable with the same name which masks the global.
var globalVar = 1;
function testFunc1 () {
globalVar = 2; //Updates the global variable
}
function testFunc2 () {
var globalVar = 5; // This variable masks the global and only updates within the scope of this function
globalVar = 3;
}
Also, you mentioned that the snippet must initialise the global before any other reference. For this I would suggest you place your script block or reference to your javascript file before any other javascript references in your element as possible. If you have other javascript files which are going to rely on the global variable then you may wish to ensure they do not load until the rest of the page has loaded first using the defer attribute. See the following:
<script src="dependant.js" type="text/javascript" defer="defer"></script>
Another option is to dynamically add your dependant scripts after your initial script has loaded. You can do this using something like jQuery as follows:
$(window).load( function() {
$.getScript('dependant.js');
});