How can I get the local variable to update the global variable?

My code:

var total_cases  = 0;
var new_cases    = 0;
var total_deaths = 0;

fetch('https://covid.ourworldindata.org/data/owid-covid-data.json')
  .then(res => {
    return res.json()
  })
  .then (raw_data => {

    for (const key in raw_data) {
      const country      = raw_data[key];
      const country_data = country.data;
      const latest_data  = country_data[country_data.length - 1];

      console.log(latest_data);

      if (country.location != "World") {
        if (latest_data.total_cases != null) {
          total_cases += latest_data.total_cases;
        }
        if (latest_data.new_cases != null) {
          new_cases += latest_data.new_cases;
        }
        if (latest_data.total_deaths != null) {
          total_deaths += latest_data.total_deaths;
        }
      }
      console.log(total_cases); /*It will give a result for every loop*/
    }
  })

document.getElementById("total_cases").innerHTML  = total_cases;
document.getElementById("new_cases").innerHTML    = new_cases;
document.getElementById("total_deaths").innerHTML = total_deaths;

If I do this:

<div id="total_cases"></div>

The result is 0. What is the code to change? I know that someone may already answered similar question about function, but I still don’t understand about scope of fetch.

51 thoughts on “How can I get the local variable to update the global variable?”

Leave a Comment