TwitchTv: help needed with variable scope

TwitchTv: help needed with variable scope
0.0 0

#1

I’m struggling with variable scope. I declared my variable channel[] as global thinking I could use it in my ajax calls. unfortunately, I get sporadic results that include often channel is undefined.

What good is a global variable if you can’t reference it in a function?

Said another way, do I need to declare channel[] in each function?

thanks.


#2

There are myriad ways this could go depending on how you wrote the rest of the app. Do you have a CodePen you can link to?

The upshot will be that global variables are bad, and the problem will probably be one of asynchronously executed code that you’re expecting to be synchronous.


#3

here it is:


#4

FYI, I’ve moved the variables around with respect to where they show up in the script. doesn’t seem to make a difference on results.


#5

and I’ve read that global variables are bad.

What I don’t know is how to translate that into my code. If I have a variable that is used in different parts of the code, it seems I need a global variable. otherwise, it seems I have to have multiple instances of a variable in different areas of the code-- which I can’t wrap my head around since it seems terribly inefficient.


#6

This is a pretty common problem that we all run into at some point in our web development career. It’s one of those things that’s confusing to understand at first, but once you get it you’re going to sail through your other projects. I’ve written a post on a similar issue here:

This isn’t your exact issue, but it’s close. Basically, your loop is running faster than the AJAX calls can go out. By the time your first AJAX call gets its response, the loop has run and the variable i is not the same as it was when the AJAX call started. While it’s not the easiest or the prettiest solution, this may be the easiest to learn right now:

for (i = 0; i < channel.length; i++) {
      var currentChannel = channel[i]; //Define your channel here
      $.ajax({
        url: 'https://api.twitch.tv/kraken/streams/' + currentChannel,
        headers: {
          "Client-ID": "gdtobx6xx8k4rcsmo6aq26braesqelq"
        },
        error: streamError(),
        success: function(data) {
          //do stuff here
          //move all DOM manipulation here
        }
      }); 
    };

The best solution right now is to use promises, which will clean up your code and eliminate the need for global variables. Check this video out Are you bad, good, better or best with Async JS? JS Tutorial: Callbacks, Promises, Generators

I actually apologize here, I can’t give you as detailed of an answer as I’d like at the moment, but I’m hoping this can get you headed in the right direction. Let me know if you have any particular questions and I’ll see if I can answer it when I’m able to focus later.


#7

thanks for the tips. I’m studying now.:no_mouth: