I’ve reformatted and annotated your loop below that uses a global counter variable x
// all references to x below are to the same global x
for(x = 0; x < twitchArray.length; x++) {
$.getJSON(
// this runs at time of iteration so global x is 0, 1, 2, ..., twitchArray.length
twitchURL + twitchArray[x] + "?callback=?",
// this async callback runs when http response is received which is likely after loop has terminated
function(user) {
// so global x is twitchArray.length
console.log(twitchArray[x]);
});
}
x
is used in an async callback function in the loop body - by the time the callback for the http response runs the value of x
is different from when the loop iteration ran
the fix below is to declare x
with let
which creates a different x
for each iteration of the loop - the value of x in the callback will be the same when the loop iteration ran
// x is declared with block scope
// each iteration of the loop refers to a different variable x
for(let x = 0; x < twitchArray.length; x++) {
$.getJSON(
// this runs at time of iteration so block scope x is 0, 1, 2, ..., twitchArray.length - 1
twitchURL + twitchArray[x] + "?callback=?",
// this async callback runs when http response is received which is likely after loop has terminated
function(user) {
// this retains a reference to the block scope x created per iteration so x is 0, 1, 2, ..., twitchArray.length - 1
console.log(twitchArray[x]);
});
}