简体   繁体   中英

JavaScript closures and a for loop

I was wondering why the result of the following code is 0 and not 3.

var fn = function(){
    for (i = 0; i < 3; i++){
        return function(){
            console.log(i);
        };
    }
}();

fn();

Because your return statement forces the loop to terminate and the function to stop executing.

You can learn more about return statements here - https://en.wikipedia.org/wiki/Return_statement

You're returning a closure that's calling console.log . When you're doing this return statement you're stopping fn() from proceeding, it returns the first thing that needs returning and halts execution. Remove the return statement (and closure) if you want to console.log.

var fn = function(){
    for (i = 0; i < 3; i++){
        console.log(i);
    }
}();

fn();

Also See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/return

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM