Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understand JavaScript scope within for-loop [duplicate]

Tags:

javascript

The following piece of code prints out "K" 16 times.

var rest = "KLMNOPQRSTUVWXYZ".split(""), fns = {};
for (var i=0; i<rest.length; i++) {
    (function(i){
        fns[rest[i]] = function() {
            console.log(rest[i]);
        };
        fns.K();
    })(i);
}

This piece of code prints out all the alphabets "K", "L" ....... "Y", "Z"

var rest = "KLMNOPQRSTUVWXYZ".split(""), fns = {};
for (var i=0; i<rest.length; i++) {
    fns[rest[i]] = function() {
        console.log(rest[i]);
    };
    fns.K();
}

I am new to JavaScript, and don't quite understand how the use of IIFE in the second example results in different behavior. Can someone please clarify?

like image 509
redandblue Avatar asked Dec 12 '25 02:12

redandblue


1 Answers

var rest = "KLMNOPQRSTUVWXYZ".split(""), fns = {};
for (var i=0; i<rest.length; i++) {
    (function(i){
        //the i inside this function is private, it is not the same i from outside, 
       //Any modification to the i from the loop won't affect this one.
        fns[rest[i]] = function() {
            console.log(rest[i]);
        };
        fns.K(); 
        // fns[rest[i]](); You should use this if for printing the correct letter
    })(i);
}

No IIFE

var rest = "KLMNOPQRSTUVWXYZ".split(""), fns = {};
for (var i=0; i<rest.length; i++) {
    fns[rest[i]] = function() { //You declare a function for each letter
        console.log(rest[i]); //This i contains always the current iteration from the loop
    };
    fns.K(); //calls the first function defined, "K" that prints the current  iteration
}
like image 67
Marcos Casagrande Avatar answered Dec 14 '25 16:12

Marcos Casagrande