Hi FCC, this is my first post!
While looking through the code for FCC weather app (I know, I’m not supposed to look), I hit something in the Javascript that I can’t seem to figure out. I think it’s a question regarding scope??
In the top of the script, global variable currentTempInCelsius is defined.
var currentTempInCelsius;
Later, this variable is assigned the temperature value from the API response within the function getWeather (with some math rounding applied). And is then immediately sent to #temp to be displayed in the html.
function getWeather(lat, lon) {
var urlString = api + lat + "&" + lon;
$.ajax({
url: urlString, success: function (result) {
$("#city").text(result.name + ", ");
$("#country").text(result.sys.country);
currentTempInCelsius = Math.round(result.main.temp * 10) / 10;
$("#temp").text(currentTempInCelsius + " " + String.fromCharCode(176));
$("#tempunit").text(tempUnit);
$("#desc").text(result.weather[0].main);
IconGen(result.weather[0].main);
}
});
}
So far this makes complete sense to me. The API is called, the response comes, the temperature gets assigned to the variable. The value of the variable gets put in the #temp text and it displays on the site. Success!
What I don’t understand:
In another area, there is a separate function used to convert Celsius to Fahrenheit. In the last line it also uses currentTempInCelsius to successfully adjust the #temp text.
$("#tempunit").click(function () {
var currentTempUnit = $("#tempunit").text();
var newTempUnit = currentTempUnit == "C" ? "F" : "C";
$("#tempunit").text(newTempUnit);
if (newTempUnit == "F") {
var fahTemp = Math.round(parseInt($("#temp").text()) * 9 / 5 + 32);
$("#temp").text(fahTemp + " " + String.fromCharCode(176));
} else {
$("#temp").text(currentTempInCelsius + " " + String.fromCharCode(176));
}
but I’m not sure how it has access to the correct value of currentTempInCelsius.
I tested a few console.logs throughout various areas of the script to see what it would give me for currentTempInCelsius:
Anywhere in the global space, it is still undefined. But within several different, unrelated, functions, the value is there!
My question: What has access to currentTempInCelsius? And where/how is that determined in this script?
I’m not sure if this is an API thing or what. I would have thought anything assigned to currentTempInCelsius would be accessible anywhere since it is a global variable.
(I hope all this makes sense! TIA)