Ian Hoar
Ian Hoar

Reputation: 1184

jQuery variable scope / call sequence

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.

Upvotes: 1

Views: 175

Answers (4)

Mrchief
Mrchief

Reputation: 76238

Scoping is not limited to jQuery. Its how javascript defines scope is what rules here. jQuery is a library built on top of javascript.

Having said that, you're declaring a global variable which is accessible to everyone. However, the assignment happens after the DOM has completed loading. While the alert statement runs immediately.

If you move the alert inside of .load after call to getMyVar(), you'll see right value being output.

Upvotes: 1

Chandu
Chandu

Reputation: 82933

It's not a scope issue.

alert is getting executed even before window.load event is triggered which is where the variable myVar is assigned the value 'test'.

As per MDN Docs:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

Upvotes: 3

Ilia Choly
Ilia Choly

Reputation: 18557

it's not a scope issue.

alert(myVar); gets run before getMyVar();

Upvotes: 0

Ned Batchelder
Ned Batchelder

Reputation: 375814

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.

Upvotes: 2

Related Questions