A classic javascript (closure) interview question

for(var i =0; i<10; i++) {
    setTimeout(function(){
        console.log(i);
    }, i);

}
//10 10times


for(let i =0; i<10; i++) {
    setTimeout(function(){
        console.log(i);
    }, i);

}
// 0 - 9


for(var i =0; i<10; i++) {
    setTimeout((function(j){
        console.log(j);
    })(i), i);

}
//0 - 9  because it's an immediately invoked function and this function returns null


for(var i =0; i<10; i++) {
    setTimeout((function(j){
        return function( ) {
            // it doesn't need to go out all the way to i to find the variable. 
            // it stores the value j the moment the outer function gets executed
            console.log(j);
        }
    })(i), i);

}
//0 - 9

Comments

  1. The allure of a giant win is comprehensible however you are much more doubtless to|prone to} be a winner this way. Every now and again, we come throughout a casino that we recommend you keep away from enjoying in} on. We have a strict 25-step review process, a 카지노 glance at} issues like a site’s software program, promotions, how easy the banking process is, safety and extra. When any of these steps fall under our requirements, the casino is added to our listing net sites|of websites} to keep away from. Unity by Hard Rock is now your virtual Wallet, a convenient various to using cash at a slot machine.

    ReplyDelete

Post a Comment

Popular posts from this blog

How to scale a website-My Approach

What is functional programming?