So I want to get data using $.getJSON and stock it in a variable to use it later. Even if I declared the variable 'subcount' before the $.getJSON, I get it as a undefined when I actually want to do something with it. My code looks like this:
function loadSubs() {
channel_url = "https://www.googleapis.com/youtube/v3/channels?part=statistics&id="+channelId+"&key="+key;
var subcount;
$.getJSON(channel_url, function(data) {
subcount = data.items[0].statistics.subscriberCount;
console.log("In scope: "+subcount);
});
console.log("Out of scope: "+subcount);
do_something_with_data();
}
The console gives me
Out of scope: undefined
In scope: 1364189
It seems like when it's coming out of the getJSON scope, the variable returns to its undefined state. I tried to initialize it with
subcount = '';
To make it global, but it does the same thing, instead of getting undefined, I get a blank string. I also think that the fact that the out-of-scope log comes first is part of the problem.
Am I missing something? If so, can you explain? Is there another way to do this?
Thanks
EDIT: I declared 'subcount' based on this answer on a different thread jQuery getJSON save result into variable