2

Version 1:

function myF() {
  var executed = false;
  return function() {
    if (!executed) {
      executed = true;
      document.getElementById("demo").innerHTML = "Ab"
    }
  };
};

myF();

Version 2:

var myF = (function() {
  var executed = false;
  return function() {
    if (!executed) {
      executed = true;
      document.getElementById("demo").innerHTML = "Ab"
    }
  };
})();

myF();

Why the v2 works, and why the v1 not? What's the main difference between these two, when they are called?

Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64
  • 1
    The second one invokes the outer function immediately, and the first does not. Add `var myF2 = myF(); myF2();` to invoke the second inner function. –  Mar 07 '18 at 22:30
  • 1
    Also, if you're not already familiar with [IIFE's](https://developer.mozilla.org/en-US/docs/Glossary/IIFE), you may want to take a look. – CRice Mar 07 '18 at 22:30
  • not an exact dupe, but close https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname – epascarello Mar 07 '18 at 22:54

1 Answers1

3

Version 2 returns the result of an IIFE, Version 1 is the same but doesn't invoke the expression. You could invoke it like myF()(),

function myF() {
  var executed = false;
  return function() {
    if (!executed) {
      executed = true;
      document.getElementById("demo").innerHTML = "Ab"
    }
  };
};

myF()();
<div id="demo">
</div>
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249