snow snow - 4 months ago 12
Javascript Question

Javascript Scope: variable declared inside as opposed to outside of a forEach loop

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
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

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
with respect to the current loop iteration. But when i declare the variable
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
is always initialised correctly in the first AJAX request irrespective of where the variable is declared.


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.