Sign in
Log inSign up

IIFE confusion in Javascript

Default profile photo
Anonymous
·Apr 5, 2018

var arr = [];

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

    }

Here I am implementing IIFE,expected output is 0,1,2.But I am getting 3 when I am running above code .I am unable to understand what is going under the hood. As per my understanding ,everytime function is called when we are pushing it in array so the required value which gets printed should be 0,1,2.