How can I use a variable that stores data from an API call outside its function. See snippet below to kinda get an idea as to what I mean:
var country;
function getLocation() {
$.getJSON('https://ipinfo.io/json', function (data) {
console.log(" 1- Your country is " + data.country);
country = (data.country);
});
}
getLocation();
var continent;
switch(country){
case "USA":
case "Mexico":
case "Canada":
continent = "Your continent is X";
break;
case "Morocco":
case "Egypt":
case "South Africa":
continent = "Your continent is Y";
break;
case "France":
case "Spain":
case "Germany":
continent = "Your continent is Z";
break;
default:
continent = "this is default text";
}
document.getElementById("myp").innerHTML = continent;
I would like to get the visitor's country and check if equals any of the predefined country, then tell display a paragraph telling him what continent he belongs to (just a sample text).
The issue is the variable country is always null once it is used outside of the get location function.