Search code examples
javascriptfunctionloopsasynchronousiife

IIFE vs function call (with parameters), inside a loop


I am confused between using an IIFE vs using a normal function call (with parameters) inside a for loop.

Lets say the function is -

function print_doc_count(i){
    var str= "collection" + i.toString();
    db.collection(str).count(function(err, res){
        if(!err){
            console.log("docs in collection: "+str+" = "+res);
        }
    });
}


Example 1 (Without IIFE) -

for(var i=1; i<=10; i++){
    print_doc_count(i);
}

Example 2 (With IIFE) -

for(var i=1; i<=10; i++){
    (function print_doc_count(i){
        var str= "collection" + i.toString();
        db.collection(str).count(function(err, res){
            if(!err){
                console.log("docs in collection: "+str+" = "+res);
                // str needed closure, it contains the value i!
            }
        });
    })(i);
}


My question is what is the difference between Example1 and Example2 above and should one be preferred over the other (under what circumstances)?


Solution

  • As stated by @Kevin B in comments to the question, Example 1 (without IIFE) is a better solution

    function print_doc_count(i){
        var str= "collection" + i.toString();
        db.collection(str).count(function(err, res){
            if(!err){
                console.log("docs in collection: "+str+" = "+res);
            }
        });
    }
    
    for(var i=1; i<=10; i++){
        print_doc_count(i);
    }