Loop frustration in Twitch Api challenge

Loop frustration in Twitch Api challenge
0

#1

Ok I’m at wit’s end. My for loop just to display the channel names that I already declared in an array won’t print to my screen. This isn’t even an Api issue (I think). Can someone show me where my code is wrong? Thanks. To be clear all I want is for the usernames in the array I’ve written at the top become part of my html inside an h2 tag. The data is logged to the console so the api call is working as it should. I just don’t know what’s wrong.

Codepen link: https://codepen.io/DebugAyem/pen/qXVvbW

function main() {

var users = [‘ESL_SC2’, “OgamingSC2”, “cretetion”, “freecodecamp”,];
var i;
var twitchProperties;
var status;
var name;

for(i=0;i<users.length;i++){
var userNames = users[i];
var twitchURL = “https://wind-bow.glitch.me/twitch-api/streams/” + userNames +"?callback=?";

$.getJSON(twitchURL,function(data) {

console.log(data);

$('.user'+i).html('<h2>'+userNames+'</h2>');

});

}

}


#3

That works perfectly! Can you explain more about the differences between .forEach() and for() and if there any other situations where .forEach would be more useful. Also where does the asynchronous request come in and why does it prevent for from happening. Cheers!


#4

If you want to use a for loop, then you must use closure via an IIFE to accomplish:

  var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp"];
  
  for (var i = 0; i < users.length; i++) {
    (function(idx) {
      var userNames = users[idx];
      var twitchURL = "https://wind-bow.glitch.me/twitch-api/streams/" + userNames;
      $.getJSON(twitchURL, function(data) {
        $(".user" + idx).html("<h2>" + userNames + "</h2>");
      });
    })(i);
  }

#6

Thanks for all the help guys. I’ll read up on the subject!!