Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda