0

I thought this would work but it does not. Is it possible to invoke a functional literal on creation like this and have it still be available for use later?

var myFunction = function() {
  alert('Hi!');
}();
riegersn
  • 2,819
  • 3
  • 17
  • 19

2 Answers2

2

If you want your function to return something meaningful you should split function creation and invocation.

If not, you could do it this way

    var myFunction = function me() {
      console.log('Hi!');
    
      return me
    }(); // first run
    
    myFunction() // second run
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
0

Easiest would be:

(myFunction = function() {
  alert('Hi!');
})();

myFunction();

Note that you may declare myFunction before it, it is considered bad style not doing so.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151