I’m having trouble understanding jQuery variable scope.
var myVar;
function getMyVar() {
myVar = 'test';
}
$(window).load(function() {
getMyVar();
});
alert(myVar);
This code will alert ‘undefined’ and I need it to show ‘test’ and I want to understand my scope issues here.
The problem is that getMyVar isn’t called until the window is loaded, while the alert is executed immediately. So the alert happens before the variable is defined. It isn’t about scope, it’s about the asynchronous execution of window load functions.