Twitch challenge - offline streamers for loop only returning last element

My Twitch viewer is almost complete but I have a minor problem with the offline streamers.

My CodePen

The online streamers is working as expected but the offline streamers should say “[name] is not online” but it repeats the last name in the array for every offline streamer. Any advise would be greatly appreciated.

You are not understanding the asynchronous nature of the $.getJSON function. Your for loop finishes iterating through the streamers array before all of the api calls are finished. Since the last item in the streamers array is FreeCodeCamp and it is assigned to names and your anonymous callback function appends uses the names variable in the offline append, you get FreeCodeCamp displayed for all of them. Since your are using var name =; at the time the data comes back within each API call for the online streamers, you actually get the correct data.

The easiest way to resolve this is by using let (ES6 syntax) instead of var in your for loop to declare the variable i=0 and then in side your $.getJSON callback function, you can use your var names = streamNames[i]; to reference the correct streamName at the time the API data comes back for that particular streamer. The let i allows i to retain its original scope value within the callback function.

1 Like