Reputation: 41417
Where do I need to place a snippet of JavaScript code that initializes a variable that must be visible to all code executed with the page? (For example, event handlers on elements will need to access this variable).
Upvotes: 19
Views: 47579
Reputation: 2128
You can do it out of any function, or in a function without using the 'var' keyword. Assign it before any other scripts (very top of the page, likely) so the scripts can read the value.
You can also place it in an included JS file, but putting it right on the page is usually more usable as you can see the global values easily, and they can be modified for each page by the server-side code. Also try to prevent assigning global variables in the body, it may make confussions and will be harder to read.
<head>
<script>
var numberOfDucks = 1000; // Global
function some_function() {
// numberOfDucks is accessible here
alert (numberOfDucks);
// until you mask it by defining a local variable using the 'var' keyword
var myLocal = 0; // is a local
anotherGlobal = 0; // is a global
}
</script>
<script>
// potentially some other script
</script>
<script src="even_more_script.js">
</head>
Defining a global in a function (implied-global) is not a good idea because it will make a lot of confussion.
Upvotes: 15
Reputation: 186662
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. It's best to avoid using the with
keyword in general.
Conclusion:
Personally, I would keep my code in an anonymous function scope, and only explicitly declare globals when I need to.
(function() {
var governor = 'Schwarzenegger',
state = 'California';
window.president = 'Obama';
})();
In the above, I define governor
and state
variables and they are local to my function. I want to explicitly define president
as a global variable. This way, I'm not confused about which variables I defined as globals or not, because I explicitly prefix them with window.
.
Upvotes: 33
Reputation: 9361
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');
});
Upvotes: 1
Reputation:
you could place that variable at the beginning of the page (in the global scope if you HAD to make it visible everywhere) but I suggest two things
1) since you have to open a script block, avoid to declare it inside the body of your page since scripts block rendering. So put it just before </head>
2) avoid to create a simple var but use a namespace instead so you reduce risks of identifier collision
<script>
var YOUR_APP_NS = {};
YOUR_APP_NS.yourvar = ....
</script>
this is a good practice in order to not polluting the global scope. If you need several public var in this way you could just write
YOUR_APP_NS.yourvar1 = ....
YOUR_APP_NS.yourvar2 = ....
YOUR_APP_NS.yourvarN = ....
but the global var is still 1
Upvotes: 4
Reputation: 1918
<head>
<script>
var b = 0;
</script>
<script src="...">
</head>
<body>
...
</body>
Upvotes: 1