Q:

Firebase data returning an UNDEFINED value even though it has content

Coming from my recent question in this site (before I resort to the "Promise" technology), I came up an idea of storing the variable in the firebase database instead of making it a global var in the javascript so that I can use it in any function (even though in an asynchronous one). So I made this code:

function logIn(){
 var loggedUname = $("#loginUname").val();
 var loggedPword = $("#loginPword").val();
 
 var tailorRef = firebase.database().ref('tailors');
 var keyRef = firebase.database().ref();
 
 tailorRef.on('value', function(data){
  data.forEach(function(childData){
   if ( (loggedUname == childData.val().tUsername) && (loggedPword == childData.val().tPassword) ){
    currentKey = childData.key;
   }
  });
  keyRef.update({currentTailor: currentKey});
  alert("key = " + keyRef.currentTailor);
 });
 
}

the .update method was successful since it stored the corresponding key for the logged in user:
the updated database
but when I try to retrieve it using alert, it says UNDEFINED! I don't understand because I'm assuming that I'm calling from the root reference of the database, that's as low as I go.
I tried making a seperate .on() function for the keyRef, but it's still the same result.

keyRef.on('value', function(data){
  alert(data.currentTailor);
});

Did I called the data in a wrong way?  

A:

The correct way would be: 
keyRef.on('value', function(data){
 //  alert(data.val().currentTailor); see the difference 
     console.log('currentTailor ==>', data.val().currentTailor);
});

alert() in javascript is not recommended as it freezes your page. Use console instead. This way you can see your logs in browser's console (in chrome press Ctrl+Shift+J)

Firebase's on() method returns the callback function . To get the data object, you have to use val() method on that return value. Then you can get any value using corresponding key.

 keyRef.on('value', function(data){
// here data is callback function
});

keyRef.on('value', function(data){
//data.val() returns the data in object form
});
 keyRef.on('value', function(data){
 // data.val().currentTailor to access currentTailor attribute
 });

You can console each of them to see what is the return values.

