In a JavaScript environment can I declare a variable before a function to make the variable reachable on a global level.
For instance:
var a;
function something(){
a = Math.random()
}
Will this make “a” a global variable?
or is using…
var a = function(){
var b = Math.random();
return b;
}
document.write(a())
Really the only way to do it?
Is there a way to make “b” global other than calling the function “a()”?
There are basically 3 ways to declare a global variable:
window.a = 'foo'.varkeyword when you first use the variable, it’ll be declared globally no matter where in your code that happens.Note #1: When in strict mode, you’ll get an error if you don’t declare your variable (as in #3 above).
Note #2: Using the
windowobject to assign a global variable (as in #2 above) works fine in a browser environment, but might not work in other implementations (such as nodejs), since the global scope there is not awindowobject. If you’re using a different environment and want to explicitly assign your global variables, you’ll have to be aware of what the global object is called.