0

I am developing an application that uses the twitch API and in the process makes two AJAX requests, one inside another. A simplified version of my code:

twitchStreamers = ["name1","name2",...];
var language, views="", html = "";
//var status;
twitchStreamers.forEach(function(streamer) {
   // some code
   $.getJSON(streamURL, function(streamData) {
      var status;
      // some code
      if(condition){
         status = "some value 1";
      } else if(condition) {
         status = "some value 2";
      } else {
         status = "some value 3";
      }
      $.getJSON(channelURL, function(channelData) {
         // some code
         // access value of status
      }) // end of second ajax request
   }) // end of 1st ajax request
} //end of forEach loop

Notice the status variable.

This design works perfectly with what i want to do i.e. when i access the status variable inside the second ajax request, it has the correct value of status with respect to the current loop iteration. But when i declare the variable status outside forEach loop it always has the value some value 3 (initialised in the else part of the conditionals) when accessed in the second AJAX request. Why is this so?

Note that the variable status is always initialised correctly in the first AJAX request irrespective of where the variable is declared.

snow
  • 455
  • 2
  • 13
  • 28
  • 3
    Because when you declare it outside the loop, there is only one variable, which can only hold a single value, not three of them? – Bergi Sep 07 '16 at 21:15
  • 2
    Do you understand [how closures work](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work), and have you had a look at [this](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example?rq=1)? – Bergi Sep 07 '16 at 21:19
  • The problem you're having here is very similar to: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example?noredirect=1&lq=1. The answers are instructive – Asad Saeeduddin Sep 07 '16 at 21:22

1 Answers1

0

This is a classic example of closures + loops. By placing the variable status outside of the forEach loop I was declaring it once. Subsequently when the loop ran and the second function started executing, it referred to the latest value that it was assigned i.e. some value 3. By placing it inside the loop, the variable will be declared not just once but at each iteration thereby storing the correct value status at each iteration.

snow
  • 455
  • 2
  • 13
  • 28