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?

4
  • 1
    Possible duplicate of How do I return the response from an asynchronous call? Commented Apr 27, 2018 at 5:55
  • 1
    Do you console.log it inside the callback function or after that? Commented Apr 27, 2018 at 5:56
  • Show us more context. Right now, it looks like you forgot to declare the variables using either var, let or const. Commented Apr 27, 2018 at 5:58
  • @Mulperi outside the callback function Commented Apr 27, 2018 at 6:06

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

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 ?
nvm. i figured it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.