0

I try to understand this code:

var funcs = [];

for (var i = 0; i < 5; i += 1) {
     var y = i;
     funcs.push(function () {
         console.log(y);
    })
} 


funcs.forEach(function (func) {
   func()
 });

The outout will be

5

5

5

5

5

And I try to understand why.

If it pushes in every iteration of the loop an anonymous function that console y, then it shouldn't push a function that console 0, a function that console 1, a function that console 2, etc?

This is what my logic says. Apparently the output is 5 times 5.

Then, if so, I try to understand the process. What it pushes in every iteration of the loop? A reference to a function that in the 'future' will go back to the loop to look for the value of y ?

And if so, will the loop then run 5 times? What I'd think is that the loop runs once, and then it should push 0,1,2...

So I'm confuse. How Javascript will execute this code? What happening when the loop runs for the first time? What function been pushes to the array?

Then, when execute the forEach loop - what happening then? in each call to the function - what's the value of y? I'm confuse, because if instead of var y = i; it will be let y = i , then it will log 0123...

But then why? If anyway the first function will invoked only after y already equal 5 - why the block scope now matters?

I'm confused and will be happy for explanation.

Thanks.

Menahem Gil
  • 787
  • 2
  • 15
  • 39
  • 1
    It will help you to understand more easily if you indent your code properly, that way you can understand which block is nested in what at a glance. – CertainPerformance Jun 12 '18 at 03:30
  • 1
    `var` doesn't have block scope in JavaScript, it has function scope. A process called *hoisting* causes all `var` declarations to behave as if they are made at the top of the function they're contained in. `let` and `const` **do** have block scope, however. – 4castle Jun 12 '18 at 03:33
  • I did it. It's not a "closure" question. I try to understand the code. I try to understand how Javascript will execute this code and why the result in each situation? (var / let). – Menahem Gil Jun 12 '18 at 03:37

0 Answers0