Msmat
Msmat

Reputation: 27

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

Upvotes: 0

Views: 280

Answers (3)

customcommander
customcommander

Reputation: 18901

There's nothing wrong with your IIFE. You are only seeing the result of the var statement. Examples:

var x = function() {};
//=> undefined
var x = 42;
//=> undefined
var x = true;
//=> undefined

An assignment expression will evaluate to the value on the right:

y = 10;
//=> 10

But the var statement itself returns nothing:

var y = 10;
//=> undefined

Relevant part of the spec:

VariableDeclaration : BindingPattern Initializer

  1. Let rhs be the result of evaluating Initializer.
  2. Let rval be ? GetValue(rhs).
  3. Return the result of performing BindingInitialization for BindingPattern passing rval and undefined as arguments.

See https://tc39.es/ecma262/#sec-variable-statement

Upvotes: 1

KooiInc
KooiInc

Reputation: 122916

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

Upvotes: 1

Mr.UV
Mr.UV

Reputation: 100

For IIFE you need to wrap your anonymous function in "( )" and then invoke it with "();" It does not allow declaration. try removing declaration.

(function() {
   var counter = 0;

   return function() {
        counter += 1;
        return counter 
   }
})();

For more info refer this. https://www.tutorialsteacher.com/javascript/immediately-invoked-function-expression-iife

Upvotes: -1

Related Questions