Doing twitch.tv json api (intermediate project)

Doing twitch.tv json api (intermediate project)
0

#1

i dont understand where m going wrong…its only a partial code…after showing the online channels…it repeats the RobotCaleb in the array instead of showing all distinct names and their status

var streamers=[“HardlyDifficult”, “ESL_SC2”, “OgamingSC2”, “adobe”, “cretetion”, “freecodecamp”, “storbeck”, “habathcx”, “RobotCaleb”];
var logo="";
var name="";
var status="";
var URL="";
var channel=“https://wind-bow.gomix.me/twitch-api/channels/”;
var streams=“https://wind-bow.gomix.me/twitch-api/streams/”;

for (var i = 0; i < streamers.length; i++) {
var channelURL=channel+streamers[i]+"?callback=?";
var streamsURL=streams+streamers[i]+"?callback=?";
$.getJSON(streamsURL,function(data1){
if (data1.stream==null) {
$.getJSON(channelURL,function(data2){
getOffline(data2);
setData();
});
}
else
{
getOnline(data1);
setData();
}
});
}

function getOnline(on){
logo=on.stream.channel.logo;
name=on.stream.channel.name;
status=on.stream.game;
URL=on.stream.channel.url;
}
function getOffline(off){
logo=off.logo;
name=off.name;
status=“Offline”;
URL=off.url;
}
function setData(){$(".content").append("

"+name+"

"+status+"

");
}

Twitch problem when clicking on buttons
#2

Change var to let in the following code.

	var channelURL=channel+streamers[i]+"?callback=?";
	var streamsURL=streams+streamers[i]+"?callback=?";

#3

its working now…thanx a lot for helping me 2nd time


#4

btw what is difference b/w “let” and “var”?


#5

Variables defined with var are known throughout the function where they are defined. (Global to the function), where as variables defined using let is only known in the block of which they are defined. let “locks in” the value of the variable at the time it is used from then on to create closure over the getJSON calls. Because getJSON is asynchronous, a var declaration would just have the last value of the variable in the for loop. In your case, streamsURL (the one used in your 2nd getJSON call) would have used the last index for i at the time the for loop finished, so all the remaining calls would have been for “RobotCaleb”.


#6

Thank you so much sir !


#7

Also, I think this video explains the differences between var, let and const very well:

I found that as a beginner, you are only introduced to var in most coding tutorials, but it seems that it is very useful to know all three of them.


#8

yupp its helpful…thanx