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?