You're doing great. I always miss a lot of things and love learning about what I've forgotten or don't yet know (there's a lot) :D
When I used to work in JavaScript and interview folks, I typically asked this question that is also solved with the use of a closure:
// what does the following return?// unfortunately, after a second passes, we get a trail of sixes,// because the function looks at `i` at invocation timefor(vari=0;i<=5;i++){setTimeout(function(){console.log(i);},1000);}// we can "fix" this by employing an immediately-invoked function expression// with closure maintaining the state of i at the time of construction// the following will now print 0, 1, 2, 3, 4, 5for(vari=0;i<=5;i++){(function(i){setTimeout(function(){console.log(i);},1000);})(i);}
You're doing great. I always miss a lot of things and love learning about what I've forgotten or don't yet know (there's a lot) :D
When I used to work in JavaScript and interview folks, I typically asked this question that is also solved with the use of a closure:
Haha, I am glad that you have mentioned this example. This is a go-to question for me too.