0

I'm wondering why the variable "gists" is not being modified in the function bellow on the arrow. It's declared outside the function so it should be global. I tried putting the variable as parameters to the functions but that doesnt work either. But when I access the variable outside the function it doesn't show that it has been modified. Is there a reason for this?

var gists; // = [];

function getGists() {

    var request = new XMLHttpRequest();

    if (!request) {
        throw 'Unable to create HttpRequest.';
    }

    var url = 'https://api.github.com/gists/public';
    //var url = 'https://api.github.com/gists/users/:smithjoe123/gists';

    request.onreadystatechange = function () {

        if (this.readyState == 4) {


            //console.log(this.responseText);


            var txt = this.responseText.trim("\"");

            gists = JSON.parse(txt);

            gists = 5544; //<<<<<<----------VARIABLE HERE NOT MODIFIED

            console.log("xxyyiii<<<<<<<<!!");
        }
    };

    request.open('GET', url);

    request.send();

}

getGists();

console.log(gists); //here it does not show that it has been modified

//console.log(gists[0].user);
Wang Liang
  • 4,244
  • 6
  • 22
  • 45
  • 1
    Because the ajax request is asynchronous, the variable ***is*** changed, it just happens later than you think. – adeneo Apr 26 '15 at 22:16
  • it displays the console.log and yet the variable is still not modified. – user3713215 Apr 26 '15 at 22:18
  • Because the variable is modified ***LATER***, when the ajax request has fetched the data and returned it. It's **asynchronous**! – adeneo Apr 26 '15 at 22:19
  • This question title begs to be closed as a duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/q/23667086/1048572) :-) – Bergi Apr 26 '15 at 22:21
  • readyState is 4 and the console.log("xxyyiii<<<<<<<<!!"); shows. I've waited on the browser and in the console it is never changed. – user3713215 Apr 26 '15 at 22:21
  • But the console log at the bottom where you log `gist` executes before the console log that logs `xxyyiii<<<<<<<<!!`, because the readystate callback executes at a later time, it's ***asynchronous*** !! – adeneo Apr 26 '15 at 22:23

0 Answers0