Reputation:
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()"?
Upvotes: 2
Views: 5601
Reputation: 219938
There are basically 3 ways to declare a global variable:
window.a = 'foo'
.var
keyword 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 window
object 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 a window
object. 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.
Upvotes: 10
Reputation: 24912
Before you think of making a variable global scope, you should consider JavaScript global namespace pollution. The more global variables you declare, the more it is likely that you application will get into conflict with another application's namespace and break. As such, it is highly important minimize the number of global variables.
Upvotes: 0
Reputation: 664503
Will this make "a" a global variable?
A var
declaration makes the variable local to the enclosing scope, which is usually a function one's. If you are executing your code in global scope, then a
will be a global variable. You could as well just omit the var
, then your variable would be implicitly global (though explicit declaration is better to show your intention).
Is there a way to make "b" global other than calling the function "a()"?
Your b
variable is always local to the function a
and will never leave it, unless you remove the var
.
Upvotes: 2