Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
JavaScript global variables not updating in functions

I am very new to JS and this is my very first post on Stack Overflow. I hope I'm doing it right.

I am currently coding a site that uses several APIs. I would like to enter the data received via these APIs into global variables so that I can reuse it in my other functions. However, I've come across several topics talking about the same issue, but I haven't found a solution for my specific case. I am very sorry if the answer is already on this site but I did not find it.

When I place console.log to debug my code, my global variables are displayed with their initial values, as if they had not been modified. But when I enter console.log myself in my browser's console, my variables are displayed with the updated value.

Here is a part of my code that does not work as I expected:

/* Here I initialise my global variables */
let cityName=" ", countryName=" ";
let lat=0, long=0;

function onload(){ //function called with body onload attribute
    getCurrentLocation();
    getTheWeatherChannel();
}

function getCurrentLocation(){
    /* API Call for IP based Location */
    $.post("https://ipapi.co/json", getLocation);

    function getLocation(data){
        cityName=data.city;
        countryName=data.country;
        lat=data.latitude;
        long=data.longitude;
        console.log(lat) //it returns the good latitude
    }
    console.log(lat) //still working
}

console.log(lat) //it returns 0 while I expected it to return the new latitude

function getTheWeatherChannel(){
    console.log(lat) //it returns 0...

    /* API Call for Weather */
    const key="*****";
    const urlCurrentInfo="https://api.weather.com/v1/geocode/"+lat+"/"+long+"/observations.json?language=en-US&units=m&apiKey="+key;
    //Here it stops working because API returns error with zero coordinates
    //...
}

I hope I have given enough information about my issue

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!