Search code examples
javascriptiife

Calling function inside IIFE


I have the following code:

function doStuff() {
    var increaseNumber = 0;

    function doSomeStuff() {
        console.log(++increaseNumber);
    }

    return doSomeStuff();
};

doStuff();

When function “doStuff” is executed, function “doSomeStuff”, which is inside function “doStuff”, gets triggered via “return doSomeStuff()” and increments variable “increaseNumber” by 1 each time it is called. If I change “return doSomeStuff();” to “return doSomeStuff;”, calling “doStuff” via “doStuff()” doesn’t work, as I’d assume.

Furthermore, I have the following code which yields the same result as the previous code:

var doStuff = (function () {
    var increaseNumber = 0;

    function doSomeStuff() {
        console.log(++increaseNumber);
    }

    return doSomeStuff;
})();

doStuff();

In this code, an IIFE is stored inside variable “doStuff”. Inside the IIFE, function “doSomeStuff” is stored and apparently gets triggered via “return doSomeStuff” and increments variable “increaseNumber” by 1 each time it is called via “doStuff()”. When I change “return doSomeStuff;” to “return doSomeStuff();”, the code doesn’t work as laid out anymore.

When:

    return doSomeStuff();
})();

//doStuff();

the IIFE and “doSomeStuff” are executed once and increaseNumber is = 1. Calling the IIFE further times via “doStuff()” doesn’t work, because of error: “JavaScript error: doStuff is not a function”.

There are mostly two things that I don’t understand here:

  1. Why does the code work when “return doSomeStuff;”. I don’t see how this triggers function “doSomeStuff”, as the () is missing. When I call a function, I make sure to add (). That’s how I learned it.
  2. ABOVE EVERYTHING: Why can I not call “doStuff” as a function when I change “return doSomeStuff;” to “return doSomeStuff();”?

You will notice that I’m still a Javascript novice rather. I hope I’m not repeating a question here (I honestly couldn’t find anything via search or on Google which would answer my query).

Thanks a million for any hints.


Solution

  • In this code, an IIFE is stored inside variable “doStuff”

    No, the IIFE is run immediately, and its return value is stored in doStuff. So if you want doStuff to be a function that you can call multiple times, you need to return a function.

    Why does the code work when “return doSomeStuff;”. I don’t see how this triggers function “doSomeStuff”, as the () is missing.

    It's not going to trigger doSomeStuff, not on its own. The code inside the IIFE is just trying to create the function, not actually run it. The spot where you call the function is the () at the end of doStuff().

    Why can I not call “doStuff” as a function when I change “return doSomeStuff;” to “return doSomeStuff();”?

    Because in that case, your IIFE is returning a number, and then that number gets assigned to doStuff.