Question: I'm have C++ and Java background. I'm having some trouble understanding function calling in JavaScript.

Below is my code example, I declared variable lon and lat #4. and assign it value on line #5 and #6. 

Here is my question, I made a call to writeToTes() on #1 and it worked. But when I placed writeToTes() on #2 or #3, lon and lat is empty, like it was never assigned. Why is that? 

according to my logic, we already executed if(navigator.geolocation){}, lat and lon should already be assigned, why is it when I made call to writeToTes() lon and lat is still empty.

```js
var lon = '',
  lat = ''; // #4 

$(document).ready(function() {
  setLonLat();
});

function setLonLat() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      lat = (position.coords.latitude); //#5
      lon = (position.coords.longitude); //#6
      writeToTes(); //#place it Here  #1
    });
    //#place it Here  #2
  }
  //#place it Here  #3
}

function writeToTes() {
  $("#tes").html(lon + " " + lat);
}
```

Answer: 
It's because `getCurrentPosition()` is an asynchronous operation. The function you pass to `getCurrentPosition()` is called a callback function. Any code put into this function is executed after the current position is retrieved.

When you place `writeToTest()` after the call to `getCurrentPosition()`, it is executed BEFORE `getCurrentPosition()` has finished executing. Therefore, `lat` and `lon` have not been assigned to yet.
It is like adding an `eventhandler` on a button click. The `eventhandler` will only fire once the button is clicked. In this case, your `eventhandler`, or `callback`, is invoked when you get a geolocation. You callback has the position which contains your `lat` and `lon` data.