Variable and Function Results Providing Different Responses when Logged to Console

Variable and Function Results Providing Different Responses when Logged to Console
0.0 0



I am working my way through the TwitchTV project, and I am having some inconsistent returns for user online status. I apologize if this topic has already been covered, but I could not find anything on it. Here is my issue.

I have created a function to return the user’s status as “Online” or “Offline”. When I console.log the function results, the returned result is accurate. However, I need to run those results in a different function, so I created a variable to equal the results and use in the second function. My problem is that this variable is not always returning accurate results. Why would the variable results differ from the function results when they are set to equal one another?

I have noted the areas of the function and variable. Thank you in advance


$.ajax is an asynchronous function, so when you try to assign a value to onAir inside the function, the assignment does not take place until the API response comes back. In the mean time, other code can continue to run which may reference onAir while waiting for the API response to come back. If onAir was declared without a value, then it is possible other code referencing onAir will show a value of undefined until the response comes back. However, the response could come back at a time when you are referencing onAir within another $.ajax call where onAir is not related to the current username you think you are dealing with.

In general, you need to reference onAir only within the original $.ajax success function, because that is the only place you are guaranteed it will be for the particular username you made the $.ajax call for.


That makes sense. Thank you for the explanation.