AJAX Call inside For loop. Console logs incorrect i value

Hello!

I am working on my Twitch API page. If you scroll down to line 58 of my Javascript (the bottom), you will see that I have pulled all of the followers into a array called “followers” (line 41-54). I am trying to loop through and get the status of each and change the image to either a check or X depending on if they are online. At the moment I am working with status0 in the html. I’ll add the others later.

If i try to console.log(i); inside the for loop but outside of the AJAX call I get the correct response: 0 1 2 3 4 5 6 7 8
When I console.log(i); inside my AJAX success function it shows i as 9.

My code may contain many mistakes because I am new. Any help or tips are appreciated!

havent got a answer but have noticed you have a for loop at line 51 like for(i=0
this makes it a global i … should use for(let i = 0 … or for(var i = 0
let would be best as it locks it to the for scope

then at line 58 you have for(i =0 … again so that will be reading your previous i (as far as im aware)
but also you create a function in this for loop which takes a i as a parameter
it is recommended that you dont create functions within a for loop

so a lot could be going on with that i … that you are not expecting … will see if i can work out if it is doing anything it shouldnt

1 Like

Found it online. Needed a “closure.”

Ah thanks for catching that! I forget to put the “var” inside my for loops too often.

Is there a better way to take the data from the array and use it in a function without using a for loop? Or are you saying I should define the function elsewhere and then just call the function instead of laying out the whole thing inside?

Thank you for your help!