1

I am storing the data from an API call in variables and I would like to use the data in the variables elsewhere in the function. However, when I printout what is in the variables outside of the arrow function, the data has a type of undefined.

The first console.log(coordinates); displays ["08002", "39.916258", "-75.021428"] and the second displays

[
    "08002",
    "39.916258",
    "-75.021428"
]

But when I have console.log(coordinates[1]); outside of the arrow function it says it's undefined.

const getLongLat = function(zip) { //gets long lat from a zip code
  zip = document.getElementById("ZipCode").value
  let lat = 0;
  let long = 0;
  let coordinates = [];
  if (zip == "") {
    zip = "08002"
  }
  coordinates.push(zip);
  const APIkey = "#########";
  let base = `http://open.mapquestapi.com/geocoding/v1/address? 
key=${APIkey}&location=${zip}`;
  console.log("base " + base);

  fetch(base)
    .then(response => response.json())
    .then(data => {

      //makes it so that the city is in the us
      let i = 0;
      while (data.results[0].locations[i].adminArea1 != "US") {
        i++
      }
      lat = String(data.results[0].locations[i].latLng.lat);
      long = String(data.results[0].locations[i].latLng.lng);
      coordinates.push(lat);
      coordinates.push(long);
      console.log(coordinates);

    })
  console.log(coordinates);
  return coordinates;
};
VLAZ
  • 26,331
  • 9
  • 49
  • 67
jonathan
  • 29
  • 1
  • 2
    There is also [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) `fetch` is asynchronous. You are accessing the array before it was populated. – Felix Kling Feb 16 '22 at 20:37
  • As for why `console.log(coordinates);` after the `fetch()` call shows the array as if it's full (also, before, for that matter): [Is Chrome’s JavaScript console lazy about evaluating objects?](https://stackoverflow.com/q/4057440) | [Weird behavior with objects & console.log](https://stackoverflow.com/q/23429203) – VLAZ Feb 16 '22 at 20:39

0 Answers0