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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With