What is the difference in the way these two functions are defined? Which is better?

//
var test1 = function(param){
    //do something
};
//
var test2 = function(){
    function test2(param){
        //do something
    }
    return test2;
}();
May.04,2021

if you want to ask which one is good, you can only say the first one. Because example 2 is a completely meaningless example, you may want to compare

//
function(){
    function test2(param){
        //do something
    }
    test2()
}();

this avoids contaminating functions with the same name in the scope.
if you are comparing the code I am talking about, it only depends on whether you need to avoid it. If necessary, use example 2 (such as plug-ins you write for others to avoid pollution), and if you don't need (all code that you can control), use example 1.


2 has an extra internal scope than 1
simply returns a function 1 well
you have to do complex operations before returning and you don't want to pollute global scope 2

var test2 = function(){
    var a = 10;
    
    function test3(n){
      return n+1;
    }
    
    function test2(b){
        return a+test3(b);
    }
    return test2;
}();

to put it simply, test2 has a scope that only it can access;


give an example of

a(1)   // 
function a (i){ ... }
a(2)   // 

b(1)  //
var b = function (i){ ... }
b(2)  //  

//...

  

Menu