0
    var rootRef = firebase.database().ref().child('Locations');

    rootRef.on("value", function(snapshot) {
             lat = snapshot.child('latitude').val();
             longi = snapshot.child('longitude').val();
             console.log(snapshot.child('latitude').val());
          }, function (error) {
             console.log("Error: " + error.code);
   });

When i console.log(lat); lat is undefined. I am new to javascript. Is there any way it can be globally available?

ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56
Samun
  • 151
  • 1
  • 1
  • 12
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Adam Azad Apr 27 '18 at 05:55
  • 1
    Do you console.log it inside the callback function or after that? – Mulperi Apr 27 '18 at 05:56
  • Show us more context. Right now, it looks like you forgot to declare the variables using either `var`, `let` or `const`. – Barthy Apr 27 '18 at 05:58
  • @Mulperi outside the callback function – Samun Apr 27 '18 at 06:06

1 Answers1

1

Your console.log(lat) that is not shown on your snippet is outside the callback function and runs before the callback when lat is still undefined. You need to do whatever you want to do with it, inside the callback when it is available.

Read this article to get to understand callback functions a little better: https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced

I hope this was any help to you!

Mulperi
  • 1,450
  • 1
  • 14
  • 24
  • Thank you so much. that worked however the value is not updating asynchronous. I thought firebase is real time. I had to refresh the browser to update. Any pointer on that ? – Samun Apr 27 '18 at 06:21
  • nvm. i figured it out – Samun Apr 27 '18 at 06:31