Reputation: 1521
I have been struggling trying to get some code to work and I think its due to my variable scopes. Instead of posting all my code here, I just made a simplified version to ask "why doesn't this work":
$(document).ready(function() {
console.log("INITIALIZE");
var aGlobalVariable = 25;
function testFunction(){
var aLocalVariable = 5;
var sumVariables = aGlobalVariable + aLocalVariable;
console.log(sumVariables);
}
});
I would expect the testFunction to be able to see aGlobalVariable, add 25 to 5, and output 30. it doesn't do this. I can't even see the global variable if I try to do a console.log of it:
Is a variable declared at the start of a document not a global one????
thanks!
Upvotes: 1
Views: 44
Reputation: 6551
aGlobalVariable
is indeed known inside testFunction. Make a call to that function and check out the console:
$(document).ready(function() {
console.log("INITIALIZE");
var aGlobalVariable = 25;
function testFunction() {
var aLocalVariable = 5;
var sumVariables = aGlobalVariable + aLocalVariable;
console.log(sumVariables);
}
testFunction();
});
Here's a jsfiddle showing this: https://jsfiddle.net/0c8rpLmj/
aGlobalVariable
is undefined when you try to view it via the console since it's not in fact global (you have defined it under the ready function scope).
Upvotes: 2
Reputation: 943142
Function expressions create variable scopes too.
$(document).ready(function() {
var aGlobalVariable = 25;
Your variable is inside a function and declared with var
so it isn't a global.
Move it outside the function expression if you want to make it a global.
var aGlobalVariable = 25;
$(document).ready(function() {
That said, making it a global probably isn't a good idea. Keeping it inside a local scope, but accessible to all the functions in that scope, means you have less change of other scripts interfering with your variable.
Upvotes: 0
Reputation: 14530
That isn't a global variable. Define it outside of the ready
function.
var aGlobalVariable = 25;
$(document).ready(function() {
console.log("INITIALIZE");
function testFunction(){
var aLocalVariable = 5;
var sumVariables = aGlobalVariable + aLocalVariable;
console.log(sumVariables);
}
});
Now you should be able to see it work.
Upvotes: 0