0

I want to create a global function inside a nested immediate invoking function. But I am getting some unexpected result. Please explain me why this is happening.

Getting a function as expected.

+function(){
 window.myFunction = function(){

 }
 window.anything = true;

 (function(){

 }());

}()
console.log(typeof myFunction);//function

Getting undefined instead of a function. I don't know why!

+function(){
 window.myFunction = function(){

 }
 (function(){

 }());
}()
console.log(typeof myFunction);//undefined
  • Put a semi-colon `window.myFunction = function(){ };` – Satpal Jan 22 '18 at 08:16
  • It's fixed by adding a semicolon after the function definition. I *think* that you assign `undefined` to `myFunction` because executing that inner function returns `undefined`. Someone correct me if I'm wrong. – Just a student Jan 22 '18 at 08:16

1 Answers1

0

You're missing a semi-colon:

+function(){
    window.myFunction = function(){

    }; // <-- You were missing this semi-colon
    (function(){

    }());
}()
console.log(typeof myFunction);//undefined

Without that semi-colon your code is equivalent to:

+function(){
    window.myFunction = (function(){

    }(function(){

    }()));
}()
console.log(typeof myFunction);//undefined

which assigns undefined to window.myFunction since the IIFE doesn't have any return statements.

Paul
  • 139,544
  • 27
  • 275
  • 264