T
T
TrainHard2015-10-18 09:53:52
JavaScript
TrainHard, 2015-10-18 09:53:52

Why does the loop output ten times undefined?

Hello!
Faced this situation:

for (var i = 0; i < 10; i++) {
  (function() {
    var i = i;
      console.log(i)
  })();
}

Why is undefined printed 10 times? After all, in theory, at each iteration in the self-calling function, the variable i is taken from the outside and assigned to the variable i , that is, from right to left (the assignment operator has right associativity)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly Inchin ☢, 2015-10-18
@TrainHard

var i  //Создать переменную i (undefined) в данной области видимости
 = i;  //Затем присвоить ей значение переменной переменной i (которую только что создали - undefined)

And it doesn't matter if you did this in the closure or somewhere else. The interpreter has such logic, and this is quite normal. And the gentlemen above, for some reason, blame everything on a self-invoking function ... one blurted out, others repeated.
The most appropriate approach is not to use the same variable names in similar schemas.

L
lega, 2015-10-18
@lega

variable i is taken from outside and assigned to variable i
It's not like that, the name "i" is captured not at the moment of var, but from the beginning of the block to the end, the same result will be if var i is moved to the end:
for (var i = 0; i < 10; i++) {
  (function() {
      console.log(i);
      var i;
  })();
}

The same with named functions, they are created immediately, and not from the point where they are published:
foo();  // вызов
function foo() {console.log('FOO') }  // объявление

I
Ivanq, 2015-10-18
@Ivanq

Here we use a self-calling function, and for it the closure mechanism works differently. It is called not in the context of the cycle, but in the root itself. It simply doesn't get passed local variables. If you need to pass, add these variables as arguments to it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question