Search code examples
javascriptiifeiif-function

JavaScript IIFE Evaluation is undefined


Hello I‘m a beginner at JavaScript and I‘m trying to figure out how IIFE work, and I still have some trouble. In the lecture I stumbled upon this example code, and the evaluation of the code below gives the result „undefined“ whereas calling the function with „add()“ returns 1 and I really don’t understand why, since function is an IIFE.

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

       return function() {
            counter += 1;
            return counter 
       }
})();
//Output: undefined

Solution

  • You IIFE is a factory function. In this case it returns a function, so that works. You can assign the result to a variable and subsequently run the resulting function. The counter variable is 'closed over', it will be manipulated (and returned) via the returned function, but it will not be accessible to the 'outside world'.

    // assign the result to a variable
    const add = (function() {
      let counter = 0;
      return function() {
        counter += 1;
        return counter;
      }
    })();
    
    // add is a function: execute it a few times
    add();
    add();
    console.log(add()); // => 3