Global Variables

Global Variables
0.0 0

#1

Need a bit of help. I can’t seem to get it to work. I’ve been using localStorage until this point.


#2

What are you trying to get to work? Global variables? You just declare a variable without using var or let


#3

Yeah, just a global variable. Ok, so don’t use var.


#4

Global variables are “global” due to their scope.

Let and var allow you to change the value assigned to a variable, const does not. That doesn’t mean the value can’t be mutated (like adding\removing\changing properties for an object).

More info on let, const, and var here.

Scope explained more here.


#5

Here’s a link to my codepen. The problem is that I the new values I push on to the global array don’t stick around outside of the scope of the callback function. OR because the callback is asynchronous, when I’m checking the variables to see that they’re there the callback hasn’t actually fired yet. Not sure! But I keep getting undefined outside of the scope of the function. https://codepen.io/attributeofextension/pen/jmrpYg/


#6

sfallmann, you’re being a bit patronizing.


#7

I was just trying to be helpful.


#8

Yeah I get that. My fault, I guess, I didn’t provide any context for the question.


#9

OK! It is something to do with asynchronous timing. I tweaked my code to show timestamps in the console for two different calls, one within the callback function and one immediately after the callback is triggered. Callback happens (app) 200 milliseconds later.


#10

I looked at your CodePen and I think you need to change how you are trying to get the data.

You need to make get requests to get the data from the server instead of adding script tags into the DOM.

Check out how with jQuery: jQuery.get()
There are other ways, but this is a simple way with lots of available examples and documentation. You will be able to add a callback to the request that gets the returned data passed into it.

Hope that helps.


#11

No that’s not right. That is how you go about doing JSONP without using jQuery. That’s what JSONP is - making use of a server-side callback function to get around CORS denials. jQuery is just implementing that for you.


#12

That’s the reason why JSONP works - because of the script tags.


#13

Ok - I’ll read up on that - I definitely stand corrected.

I’ve never done it that way and completely forget that about the CORS problem.

When I did that challenge, I didn’t make the requests directly to the Twitch API - I used the intermediary provided.


#14

What intermediary? Do you just mean jQuery?


#15

Free Code Camp Twitch API Pass-through
https://wind-bow.glitch.me/


#16

So I think I solved my own problem. I think this codepen demonstrates what’s up with the timings: https://codepen.io/attributeofextension/pen/KmMBEp?editors=0010


#17

That definitely clears up the timing of everything.