I am trying to access the rate variable from outside the function in which it is defined. I have declared a global rate variable but it is "undefined" at the point I need to use it. I've minimized the code to keep it as clean as possible.
var db = firebase.firestore();
var docRef = db.collection("pricing").doc("default");
var rate; //Setting up global variable to store value
docRef.get().then(function(doc) {
console.log("Document data:", doc.data().base); //This works
rate = doc.data().base;
console.log("Rate:", rate); //This works
});
console.log("Rate:", rate); //rate is "undefined" but rate variable value
//is accessible if typed via the console?
console.logon the last line gets executed beforeget()is resolved. You should read up on promises and how JavaScript handles asynchronous code to learn more about this behavior.