Please help to answer the following questions

Why is the result of the execution of the following functions 2? Hasn"t counter been reinitialized each time it is called? Also, () () executes the function immediately, so why use var add =. Counter? is not called in return when add () is defined Confused for a long time, please help me to answer

var add=(function(){
        var counter=0;
        
        return function(){
        counter+=1;
        }
        
        })();
        
add();
add();//2
Apr.15,2021

you can change it to

var add = (function() {
    var counter = 0;

    return function() {
        counter += 1;
        console.log(counter)
    }

});

add()();
add()(); //1

first add is an immediately executed function expression, creating the variable counter in the F1 function scope, and then accessing counter (the so-called closure) under the F1 lexical scope in the f2 scope, which is the so-called closure.

var add=(function f1(){
        var counter=0;
        
        return function f2(){
        counter+=1;
        }
        
        })();
        
add();
add();//2
Menu