0

I am currently having trouble understanding the following Javascript code and after searching a bit I still cannot figure it out. I've included the function below

function buildFunctions(){

    var arr = [];

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

    return arr;
}


var fs = buildFunctions();

fs[0]();
fs[1]();
fs[2]();

Question: Can someone please help me understand why the following code produces all 3's instead of 0, 1, 2?

I'd really like to understand exactly what's going on here, but I don't see why the functions doesn't output 0, 1, 2

Ockham
  • 455
  • 1
  • 6
  • 16
  • 1
    Can you post raw code? – kind user Jan 05 '17 at 13:10
  • I would suggest reading about javascript closures. In this example, each `i` is a reference back to the scope in which the anonymous function is created. – Davin Tryon Jan 05 '17 at 13:10
  • read this http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Himanshu Tanwar Jan 05 '17 at 13:12
  • I've edited my question and I'll make sure to post code next time, sorry about that. Also, thanks for the linked to question!! That's exactly what I was looking for! Thanks – Ockham Jan 05 '17 at 13:17

0 Answers0