Forum Moderators: open

Message Too Old, No Replies

JavaScript Global Variable

         

JAB Creations

8:45 pm on Apr 20, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How do I make a variable global in JavaScript?

- John

httpwebwitch

1:27 pm on Apr 21, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Define it outside the scope of your functions.

<script>
var d;
function add(){
/* these are scoped within the function, using var. */
/* a,b, and c do not exist outside the "add" function. */
var a = 1;
var b = 2;
var c = 3;
/* this one already exists outside the function, */
/* and we're not using var, so it's global */
d = a+b+c;
}
add();
alert(d);
// this alerts "6"
</script>

Fotiman

3:40 pm on Apr 21, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Method 1: Explicitly declare it outside of any function scope:


var g; // This is global

Method 2: Implicitly use a global variable by not using 'var' inside the function scope:


function x() {
var a = "bye"; // This is only defined in the scope of x
g = "hello"; // g was not var'ed, so it's a global
}
x(); // Run x
alert(g); // alerts "hello" because g is global
alert(a); // a is undefined

Method 3: Define a variable in the window scope:


function x() {
window.g = "hello";
}
x();
alert(g);

httpwebwitch

4:59 pm on Apr 21, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



ooh, good one Foti. I forgot about attaching to the window object.
You can attach a variable to the window explicitly, since the window object exists everywhere at once, regardless of scope.

Best practice is to combine Methods 1 and 2; declare outside the function, *and* use it within sans-var.
Or use Method 3 which is just as good.

Fotiman

5:15 pm on Apr 21, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Best practice is to avoid globals whenever possible. :) Instead, have only 1 global variable which contains an object, and then any additional variables that need to be shared between methods can be properties of that object.


var g = {
a : "bye",
b : "foo"
}
alert(g.a);
alert(g.b);

stuartc1

10:24 am on Apr 22, 2008 (gmt 0)

10+ Year Member



....have only 1 global variable which contains an object, and then any additional variables that need to be shared between methods can be properties of that object.

Great tip, very simple but effective method. Thanks :)

Fotiman

3:42 pm on Apr 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



@stuartc1
Try googling for "javascript namespacing" for more details. :)