Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda