0

I'm learning javascript but stuck on one thing that, I have created an empty object and trying to mutate its value inside a function, and problem is that when I access the changed value from inside the function it shows but when I try to access object key and value from outside the function I get UNDEFINED.

Here is the code

"use strict"
    
//Fetch auto location
    
let user_location = {};
    
if (navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(showPosition);
} else { 
   console.log("Geolocation is not supported by this browser.");
}
    
function showPosition(position) {
   console.log(position.coords.latitude,  position.coords.longitude)
   user_location.lat = position.coords.latitude,  position.coords.longitude
   user_location.lon = position.coords.latitude,  position.coords.longitude
    
   //This shows the data perfectly
   console.log(user_location)
};
    
    
//But This shows undefined 
console.log(user_location.lon)
BadPiggie
  • 5,471
  • 1
  • 14
  • 28
  • The function `showPosition` is only called after the main script has completed. In other words, it is called asynchronously. You cannot expect to print the result now, when it is only coming in some future. – trincot Aug 29 '21 at 14:26
  • `getCurrentPosition` is taking `showPosition` as a `callback`. This means it will only execute the `showPosition` after it fetch the geolocation successfully. Until that, The `user_location. lon ` will remain `undefined`. – BadPiggie Aug 29 '21 at 14:30
  • Are all functions asynchronous in javascript? – Kartik Jobs Aug 29 '21 at 14:30
  • @KartikJobs Not all the functions. If a task needs time to complete, But you don't want the user to wait until that. So you can use `Async` functions. In this case, `geolocation` methods obviously need time to fetch the exact location. But you can't stop other executions until they finish. That's why it takes `callbacks`. Once it's done with the job, It will notify by calling the `callback`. – BadPiggie Aug 29 '21 at 14:36

0 Answers0