Search code examples
javascriptiifehoisting

IIFE and function hoisting - is not a function error


var Mod=(function () { say('hello'); 
             var say =  function (m){ console.log(m); }; 
              return ({a: 'b'}); }
 )();

VM3488:1 Uncaught TypeError: say is not a function(…)(anonymous function) @ VM3488:1(anonymous function) @ VM3488:1

but this works

var Mod = (function () { 
              say('hello');  
              function say (m){ console.log(m); };
              return ({a: 'b'}); }
     )();

why is this happening ? If I need to use "say" as a public function in my Mod, how is that going to work ?


Solution

  • That's because function expressions are not hoisted. The first one is a a function expression and the second one is a function statement which is hoisted.

    Also note that neither of your code snippets exports the say function so it remains as a private function.