0

I am having a really hard time with functioning of javascript, and I will explain it with this piece of code (lets say patients size is 3):

for(j=0; j<patients.length; j++){
            console.log("before function - "+j);
            DButils.getDaysLeft(patients[j] , function(daysLeft){
                console.log("inside function - "+j);
            });
            console.log("end - "+j);
        }

This is the output I get:

before function - 0
end - 0
before function - 1
end - 1
before function - 2
end - 2
inside function - 3
inside function - 3
inside function - 3

because of that problem, if I do patients[j] inside the function it always gives me undefined, obviously because patients is only at the size of 3.

I understand that the function functioning as a thread and therefore the loop ends before we enter the callback of the function, but how do I solve it? what can I do to make it work as a normal 'for loop' like c# or java would work with that piece of code?

linusg
  • 6,289
  • 4
  • 28
  • 78
Guy Ben-Moshe
  • 874
  • 1
  • 15
  • 23
  • Welcome to JS. You must have been confused a lot. Make the `function(daysLeft){console.log("inside function - "+j)}` function definition an IIFE and save `j` under a closure. Like `(function(daysLeft){console.log("inside function - "+j)})(j);` – Redu Mar 25 '16 at 11:54

1 Answers1

2

JavaScript have function level scope not block level scope.

Use closure, it remembers the value of a variable in which it is created.

Try this:

for (j = 0; j < patients.length; j++) {
  console.log("before function - " + j);
  DButils.getDaysLeft(patients[j], (function(j) {
    return function(daysLeft) {
      console.log("inside function - " + j);
    }
  })(j));
  console.log("end - " + j);
}
Rayon
  • 36,219
  • 4
  • 49
  • 76