1

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.

0

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

Okay, totally makes sense, this is for a jQuery plugin, does this mean I have to wrap the entire thing inside the $(window).load ?
That would be a way to fix it.
Ian: You should follow these guidelines: docs.jquery.com/Plugins/Authoring They will show you the awesomest ways to construct your plugins. Almost everything you do should be done on document ready and not immediately.
1

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.

Comments

0

it's not a scope issue.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.