0

I am trying to loop an array using for loop. As soon as the variable goes inside the firebase query, only the last value is displayed. Any idea why this is happening?

const handleClose = () => {
        var tpList = TP;
        for (var v in tpList) {
            var tp = tpList[v];
            console.log(tp);
            Firebase.database().ref("Student").child(tp + "/Name/").once('value').then((res) => {
                console.log("Name of " + tp + " is " + res.val());
            })
        }

The first console log works perfeclty fine, showing the correct values from index 0-5. However, the second console log shows only the index value of 5. Any suggestions what could be wrong here?

1 Answers1

0

As mentioned in the comment, you'd use let instead of var in the loop:

const handleClose = () => {
    var tpList = TP;
    for (let v in tpList) { // Use let here
      let tp = tpList[v];   // (optional) Also here to keep the scope inside the loop
      console.log(tp);
      Firebase.database().ref("Student").child(tp + "/Name/").once('value').then((res) => {
        console.log("Name of " + tp + " is " + res.val());
      })
    }

The reasons for this is that in ES6 when using let in a loop, the declared variable will get a new binding for each iteration of the loop, so the closure will correctly capture each value of v, instead of capturing only the last one as it happens when using var.

Clarity
  • 10,730
  • 2
  • 25
  • 35
  • 1
    Please do explain on why let instead of var inside a for loop, probably some insights about lexical scoping of variables in java script.... – vaibhav Sep 16 '19 at 10:22