0

I am new to Javascript and am trying to pull geolocation data (longitude/latitude) from the browser. I am trying to understand the scope of the let variables lat and long.

When printed to the console, I receive the following output:

3: undefined

2: undefined

1: 40.112

Why do I receive undefined in the console at all?

window.addEventListener('load', () => {
  let lat;
  let long;

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position => {
      lat = position.coords.latitude;
      long = position.coords.longitude;

      console.log('1: ' + lat)
    })
    console.log('2: ' + lat)
  }
  console.log('3: ' + lat)
})
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

1 Answers1

2

It's because getCurrentPosition is asynchronous: it'll run in the background while the code afterwards keeps running, then it'll call the callback function once it finishes. So, you queue up the getCurrentPosition, then before it's finished, you log 2: lat and 3: lat, which are both undefined due to not being set yet.

Then, once you finally get the position, the function is called and 1: lat is logged, where the value is finally set.

Aplet123
  • 33,825
  • 1
  • 29
  • 55