Forum Moderators: open
<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>
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);
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.