-2

I came across this code, which I don't understand what is going on, and then I removed the IIFE parenthesis and the console.log didn't work anymore, can someone explain what is going on, It is called the classic module pattern. Why we want to use it?

var foo = (function(){
  var publicAPI = {
    bar: function(){
      publicAPI.baz()
    },
    baz: function(){
      console.log('baz')
    }
  }
  return publicAPI
})()

foo.baz()
foo.bar()

removing the IIFE parenthesis the console.log doesn't work anymore.


var foo = function(){
  var publicAPI = {
    bar: function(){
      publicAPI.baz()
    },
    baz: function(){
      console.log('baz')
    }
  }
  return publicAPI
})

Thank you a lot in advance.

Jason
  • 67
  • 7

2 Answers2

-1

Given:

foo = function () {}

foo is that function.

Given:

foo = function () {}();

foo is the return value of that function.


If you don't call the function, then foo gets a different value.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

In the IIFE you are executing the anonymous function inside the first pair of parenthesis (function(){...})() which returns an object having the bar and baz methods inside it.

so after the execution of the IIFE foo refers the publicAPI object, on which you call the bar and baz methods.

If you remove the parenthesis it just becomes a function statement which does not execute the function or returns the publicAPI object. So foo would refer to the function object and until you execute it foo.bar() or foo.baz() won't be available.

//foo is just referring to the function object if you don't execute it
var foo = function(){
  var publicAPI = {
    bar: function(){
      publicAPI.baz()
    },
    baz: function(){
      console.log('baz')
    }
  }
  return publicAPI
}
//Execute foo to get the returned publicAPI object
foo().bar();
foo().baz();

So surrounding a function definition with a parenthesis converts it to an expression and expressions can be invoked.

(function{...}) --> Expression

You can invoke this expression and assign the returned value to variable (in your case it is foo).

var foo = (function{...})() --> Executed the function expression, foo contains the result of the invokation
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44