Understand JavaScript scope within for-loop -


this question has answer here:

the following piece of code prints out "k" 16 times.

var rest = "klmnopqrstuvwxyz".split(""), fns = {}; (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 alphabets "k", "l" ....... "y", "z"

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

i new javascript, , don't quite understand how use of iife in second example results in different behavior. can please clarify?

var rest = "klmnopqrstuvwxyz".split(""), fns = {}; (var i=0; i<rest.length; i++) {     (function(i){         //the inside function private, not same outside,         //any modification loop won't affect one.         fns[rest[i]] = function() {             console.log(rest[i]);         };         fns.k();          // fns[rest[i]](); should use if printing correct letter     })(i); } 

no iife

var rest = "klmnopqrstuvwxyz".split(""), fns = {}; (var i=0; i<rest.length; i++) {     fns[rest[i]] = function() { //you declare function each letter         console.log(rest[i]); //this contains current iteration loop     };     fns.k(); //calls first function defined, "k" prints current  iteration } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -