Skip to content Skip to sidebar Skip to footer

Unable To Update Global Variable Inside A Function And Call It Outside It (jquery)

I've read some other questions about this topic and many say that if I declare the variable varA outside my function (in de global scope), it is a global function, and so it is acc

Solution 1:

The issue is that there's a race condition for accessing varA: if the code below the $(function() {}); runs before the code inside the function, then it will not be defined.

In this case, $(document).ready() is the same thing as $(), so the document should already be ready inside the function. Thus, you can just run

$(function() {
    var varA;

    varA = 'varA has been altered!';
    alert(varA); //displays 'varA has been altered!'
});

This isn't an issue with scoping: here's an example where the scoping is similar, but the race condition is removed, so the code will work:

$(function() {
    var varA;
    var def = $.Deferred();
    def.then(function() {
        varA = 'varA has been altered!';
    }).then(function() {
        alert(varA); //displays 'varA has been altered!'
    });

    def.resolve();
});

Solution 2:

As @mc10 mentioned this is primarily happening due to the race condition for accessing varA. This is happening because $(document).ready() waits for the readystatechange event to fire as being ready before callback gets called, however it also runs setTimeOut to check if the readystatechange event has already fired.

Thus any code like :

$(document).ready(function(){
    a();
    $(b);
    c();
});

Will execute in order

  1. a

  2. c

  3. b

Solution 3:

By default, javascript variable get 'undefined' as the value untill they have been assigned some value. in this case your inner function is not getting execute first and out alert gets execute first and at that time value of the variable is 'undefined' so you gets the same.

to avoid this you may try as below.

        $(document).ready(function () {

        var varA;

        (function () {

            varA = 'varA has been altered!';
            console.log(varA); //displays 'varA has been altered!'

        }());
        console.log(varA); //displays 'varA has been altered!'
    });

Post a Comment for "Unable To Update Global Variable Inside A Function And Call It Outside It (jquery)"