eRodY eRodY - 5 months ago 9x
Javascript Question

JavaScript - Only the first part of if statement gets evaluated

In my code I'm looping over an array of usernames(called users) to make an API call with each of them. The code for that looks like this:

for(user in users){
var username = users[user];
console.log(username); //it iterates over every user in the array
cbJSON(username); //that means this function is called for each user

The cbJSON function takes one argument, the username, and makes an API call. Then it should write to the console if the user is online, offline or doesn't exist. For that I'm using an if statement that evaluates if is true, null, or undefined like this:

function cbJSON(name){
$.getJSON(url + name + cb, function(data){
var ds =;

//Problem: Only the initial if statement works.
//The else if and else statements are NEVER called

//Only this works
//handle user is online
//show status, name, game, viewers, resolution

console.log(name + ' is online.');

//this is never called, even though it should be
} else if(ds === null) {
//handle user is offline
//show status, logo and name
console.log(name + ' is offline.');

//this is never called, even though it should be
} else {
//handle user does not exist
//error message: user does not exist
console.log(name + ' does not exist.');

ds should evaluate to true whenever exists and isn't falsy.

ds equals null when the stream is offline.

ds equals undefined when the channel doesn't exist.

Only the first part if this if statement seems to get evaluated. If someone in the users array is online, 'username is online' gets written to the console. However, most users in the array are offline and one doesn't exist, so those should also get written to the console as 'username is offline' and 'username does not exist'.

This is a rather simple if statement, and I didn't think I'd run into any trouble here, but I can't figure out why this isn't working as expected. I'm just gonna link my codepen here, because it is possible that the problem lies somewhere else:

One more thing: The if statement was working yesterday, but I changed a bunch of stuff since then, including how the cbJSON function is called, and it has since stopped working properly.

I'm still somewhat new to JavaScript, so it's likely that I'm missing something obvious here, but I can't figure it out on my own. Believe me, I've tried.

I would be very glad if anyone was able to help me on this.


Found the bug.

You do a bunch of assignments after assigning ds

var ds =;
var linkStream =;
var logo =;
var displayName =;
var game =;
var viewers = ds.viewers;
var resolution = ds.video_height;
var preview = ds.preview.small; 

You also said that when the streamer is offline ds should be null right? Well, in Javascript, if you try to get a property of a null or undefined variable you'll throw an error and the rest of the function will not be executed. So, I fixed your pen for you: it works now :).

I hope I helped, thanks.