title: Variable from firebase database isn't seen globally despite outer declaration. (javascript)
body: <p>I have been doing research for the past few hours on local and global variables. What I found from this question "<a href="https://stackoverflow.com/questions/10872006/how-do-i-change-the-value-of-a-global-variable-inside-of-a-function">How do I change the value of a global variable inside of a function</a>", and a few others was that if the variable was stated before the function (outside of it) then when you want to update the variable in a function you just say the "variable = blank" without "var" proceeding it.</p>
  
  <p>If you look at the function below I have three alerts, all alerting the username of the currently logged in user via firebase. The first alert, inside the firebase reference, displays the username no problem. The other two alert "undefined". I need to be able to reference the variable in all three locations, is there something I did wrong? or is there another way to do this that works and is maybe more efficient?</p>
  
  <pre><code>var database = firebase.database();
  var username;
  
  function initApp() {
    // Listen for auth state changes.
    // [START authstatelistener]
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
        var displayName = user.displayName;
        var email = user.email;
        var emailVerified = user.emailVerified;
        var photoURL = user.photoURL;
        var isAnonymous = user.isAnonymous;
        var uid = user.uid;
        var providerData = user.providerData;
  
        var ref = firebase.database().ref("users/" + uid);
        ref.once("value").then(function(snapshot) {
          username = snapshot.child("username").val();
          alert(username);
        });
        alert(username);
      }
    });
  }
  alert(username);
  
  window.onload = function() {
    initApp();
  };
  </code></pre>
  
  <p>I understand this may seem similar to other questions, but those answers didn't seem to work despite numerous different approaches. Thanks in advance for all of your help, I am hoping this is just a stupid mistake.</p>