2
    var data = ["s","a"]
    var asyncFunctionss = [];

    for (var i in data) {
        asyncFunctionss.push(function (callback) {
            console.log(i);
        });
    }
    for (var g in asyncFunctionss) {
        asyncFunctionss[g]();
    }

I try to run this program it give the following output.

Expected Output

0

1

Actual Output

1

1

How to achieve the Expected output ?

vimal prakash
  • 1,434
  • 1
  • 18
  • 35

1 Answers1

2

You need an IIFE. The reason is that as soon as a function element in asyncFunctionss is called the variable i is already 1. You could use a IIFE to remember the value of variable i:

var data = ["s","a"]
var asyncFunctionss = [];

for (var i in data) {
  (function(i){
    asyncFunctionss.push(function (callback) {
        console.log(i);
    });
  })(i);
}
for (var g in asyncFunctionss) {
    asyncFunctionss[g]();
}
Community
  • 1
  • 1
Blauharley
  • 3,936
  • 6
  • 25
  • 45