Javascript - What is the output: var variables declarations in for loops?


What is the output of the following code?

For loops (for, for-in, for-of) allows you to declare variables in their statement.

In a basic for-loop, using var creates a single binding for that variable

let arr = []; 

for (var i=0; i < 3; i++) { 
    arr.push(function () { return i }); 

let value = arr[0](); 


Click to view the answer



You might have expected the output to be 0, but the output is 3.

A closure gets created over the variable i at the end of the loop.

i is set to 3 and each instance of i in the body refers to the same binding.

Therefore, the function always returns 3.