user2290820
user2290820

Reputation: 2759

Javascript IIFE: Immediately Invoked Function Expression execution. how it runs?

I am trying to understand how IIFE in JS works.

I first ran this:

(function boo() {
      var i = 90;
      console.log(i);
    })();

and adding below

boo();

doesn't run.

Q1: Why? is this named iife not stored for reference to be called later on?

When I do this

 var tee = function boo() {
  var i = 90;
  console.log(i);
};

tee();

boo();

it runs

but when I do this

 var tee = function boo() {
  var i = 90;
  console.log(i);
};

boo();

tee();

It doesn't run.

Q2: Why?

Upvotes: 1

Views: 133

Answers (1)

Felix Kling
Felix Kling

Reputation: 816462

Q1: Why? is this named iife not stored for reference to be called later on?

Basically yes. The name of a function expression does not become a symbol in the enclosing scope. E.g. if you have

var foo = function bar() {
  // `bar` is defined here, `foo === bar`
};
// only `foo` is defined here

then you can only access foo. bar is only accessibly within the function (and refers to the function itself). See Named function expressions demystified for more info.

Q2

This has nothing to do with IIFE. Both of them are actually broken.

The reason why you don't see an output in the second example is because you are trying to access boo (which does not exist) before calling tee (which does exist).

JavaScript stops executing the code when it throws an error, hence tee is never called.

Upvotes: 2

Related Questions