Hello
So i’ve been stuck on this for the better part of 2 days now, basically when I try to reference my for loop variable within a getJSON function it doesnt work.
On line 11 and 12 in the JS, I’ve got 2 console logs, where “names” is the array of strings of twitch streamers names.
console.log(names[0]);
console.log(names);
both are within the json function within the for loop yet names logs undefined while names[0] logs what it should.
Thanks to anyone that can help, i’ve spent days on this roadblock.
Haiiiiyo.
If I’m not mistaken this is a common variable scope problem that’s well documented:
Alternatively, you can also take advantage of the ES6 let
as it is scoped to the enclosing for loop, for example:
for(let x = 0; x < names.length; x++){
...
jQuery.getJSON(channelsURL + names[x], function(data) {
console.log(x) // Returns 1, 2, 3, 4... It's more than likely not in this order because of the asynchronous nature of jQuery.getJSON()—but the "correct" x will be matched to the one in names[x]
});
}
console.log(x) // Variable not defined, as it is inaccessible outside of the for loop
Contrast the above to what you are currently getting with var
:
for(var x = 0; x < names.length; x++){
...
jQuery.getJSON(channelsURL + names[x], function(data) {
console.log(x) // Returns names.length, names.length, names.length, names.length...
});
}
console.log(x) // Returns names.length
I hope that helps. 
Thank you, after all that time all it took was let.