0

This code snippet works perfectly fine

const foo = 2;
(function (){
    console.log(foo);
})()

Now I added a variable foo which is a function, But the following code snippet doesn't work,

const foo = function(){ return "foo" }
(function (){
    console.log("aa");
})()

This throws error: TypeError: (intermediate value)(...) is not a function

However, moving the function object within the scope of IIFE works fine (obviously),

(function () {
    const foo = function () { return "foo" }
    console.log(foo())
})()

Node version(s): v12.12 / v10.16

Questions:

Is this the only way when working with IIFE ?

What exactly is happening with second snippet?

nmxl
  • 962
  • 1
  • 8
  • 22

0 Answers0