0

I get the data from firebase and it shows up in the console but only if I use it inside a function. I need to pull them out so I can use them for example in another script. What am I doing wrong? I've looked for solutions on the internet and I don't quite understand why it doesn't see them except for the function. Sorry if the question is of the basic ones, I am just starting to learn js.Thanks for help in advance!

var ref = firebase.database().ref();

 ref.once("value", function(snapshot) {
    var lux= snapshot.val().Weather.updated.lux;
    console.log("lux:",lux);
    return lux
  }, function (error) {
    console.log("Error: " + error.code);
  });

console.log(lux) // at this point I got an error  - 'lux' is not defined  no-undef

I tried elsewhere to declare a variable but it always didn't see it or didn't assign a value. I also tried fetching the data in other ways but always using a function so the problem didn't go away

kara6667
  • 3
  • 3
  • There are two reasons: 1. [`lux` isn't in scope there](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript), you've only declared it **within** your callback function, so it doesn't exist *outside* your callback function. 2. Even if it were in scope, it [wouldn't have a value yet](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). – T.J. Crowder Oct 30 '22 at 09:23

0 Answers0