6
var module = {};


(function(exports){

  exports.notGlobalFunction = function() {
    console.log('I am not global');
  };  

}(module));

function notGlobalFunction() {
  console.log('I am global');
}

notGlobalFunction(); //outputs "I am global"
module.notGlobalFunction(); //outputs "I am not global"

Can anyone help me understand what's going on here? I get that if you call notGlobalFunction(), it will just call the second function.

But what is var module = {} doing? and why is it called again inside the first function?

It says this is commonly known as a self-executing anonymous function but I don't really know what that means.

Mark Karpov
  • 7,311
  • 2
  • 24
  • 54
satisfiedLemon
  • 65
  • 1
  • 1
  • 3

4 Answers4

25

Immediately invoked functions are typically used to create a local function scope that is private and cannot be accessed from the outside world and can define it's own local symbols without affecting the outside world. It's often a good practice, but in this particular case, I don't see that it creates any benefit other than a few more lines of code because it isn't used for anything.

This piece of code:

(function(exports){

  exports.notGlobalFunction = function() {
    console.log('I am not global');
  };  

}(module));

Would be identical to a piece of code without the immediate invocation like this:

module.notGlobalFunction = function() {
   console.log('I am not global');
};  

The one thing that is different is that in the first, an alias for modules called exports is created which is local to the immediately invoked function block. But, then nothing unique is done with the alias and the code could just as well have used modules directly.


The variable modules is created to be a single global parent object that can then hold many other global variables as properties. This is often called a "namespace". This is generally a good design pattern because it minimizes the number of top-level global variables that might conflict with other pieces of code used in the same project/page.

So rather than make multiple top level variables like this:

var x, y, z;

One could make a single top level variable like this:

var modules = {};

And, then attach all the other globals to it as properties:

modules.x = 5;
modules.y = 10;
modules.z = 0;

This way, while there are still multiple global variables, there is only one top-level global that might conflict with other pieces of code.


Similarly, an immediately invoked function creates a local, private scope where variables can be created that are local to that scope and cannot interfere with other pieces of code:

(function() {
    var x, y, z;

    // variables x, y and z are available to any code inside this immediately invoked function
    // and they act like global variables inside this function block and
    // there values will persist for the lifetime of the program
    // But, they are not truly global and will not interfere with any other global
    // variables and cannot be accessed by code outside this block.
    // They create both privacy and isolation, yet work just as well


})();

Passing an argument into the immediately invoked function is just a way to pass a value into the immediately invoked function's scope that will have it's own local symbol:

(function(exports) {
    // creates a local symbol in this function block called exports
    // that is assigned an initial value of module
})(module);
guypursey
  • 3,004
  • 3
  • 21
  • 40
jfriend00
  • 637,040
  • 88
  • 896
  • 906
  • 1
    thanks for the detailed answer. I really appreciate it! XD love this community. – satisfiedLemon Jan 14 '13 at 17:06
  • 1
    Good answer with nice attention to formatting. But instead of 'self-executing' function, it should be 'immediately invoked'; an important distinction. A 'self-executing' function would call itself from within itself. The parentheses after this kind of anonymous function merely call the function and are actually themselves *outside* the function's scope (therefore it is execut*ed* immediately, but not *self*-executing). I've made an edit to reflect this. – guypursey Jan 14 '13 at 17:20
  • @guypursey - I don't get why you think the phrase `self executing function` would be confusing to anyone or why `immediately invoked function` is a better way to communicate the concept. 'self executing function` is a commonly used phrase and seems to me a clear way to describe what is going on (note it was also used in the OP's question title) and I'm unaware of how it could be confused for anything else. I have not reverted your edit, but I am not convinced that your term is a better way to describe it. – jfriend00 Jan 14 '13 at 17:38
  • @guypursey - Note the technically correct description would be something like `immediately invoked anonymous function expression`, but nobody wants to use that phrase in normal writing so I used a shorthand descriptive phrase `self executing function` which is only meant as a descriptive shorthand that is easy to associate with the concept. – jfriend00 Jan 14 '13 at 17:48
  • @jfriend00 Thanks for accepting the edit and sorry if it seems pedantic. The term was used in the question so I understand why you were using it in your response. Perhaps the question should also reflect this, or the answer could include a line like 'The pattern provided is not actually a self-executing function but an immediately invoked one.' I think the distinction is important as it is possible to have an *actually* self-executing function, i.e. one that calls itself from within. That's a very different thing from a function which is invoked immediately in order to create a closure. – guypursey Jan 14 '13 at 18:42
  • @jfriend00 `Immediately invoked anonymous function expression` might be more accurate but the focus here is on the fact that the function is immediately invoked, not that it is anonymous. `Immediately invoked 3-line anonymous function with one method` would be more accurate still but not useful as a term. `Immediately invoked function expression` *is* only one word shorter, but you can use `immediate function` or the acronym `IIFE` for short. `Self-executing function` on the other hand is inaccurate and therefore misleading. Again, sorry if it seems pedantic. Hope the change makes sense now. – guypursey Jan 14 '13 at 18:48
  • @guypursey - I disagree. We're talking about what makes a better shorthand phrase for common use to describe the construct. This is a construct which executes itself (e.g. self executing). IIFE means nothing to someone who doesn't know what it is. That's an abbreviation, not a shorthand descriptive phrase. – jfriend00 Jan 14 '13 at 19:00
  • @jfriend00 Agree with you that IIFE means nothing to someone who doesn't know what it is. That's why I didn't include it in my edit of your answer. But `immediately invoked function` is a shorthand descriptive phrase, just like `self-executing function`. And I disagree that what we see here is a construct which executes itself. [*This*](http://jsfiddle.net/guypursey/bWB73/1/) is a self-executing function, which I created as an example to explain what I mean. If you check the console after it's run you will see that `power()` is called four times but only once outside itself. Hope this helps. – guypursey Jan 14 '13 at 19:23
  • @guypursey - no point in continuing the debate. I don't think your example is self-executing because it doesn't execute without being called first externally. Your example is recursive (e.g. it calls itself from inside the function body). – jfriend00 Jan 14 '13 at 21:34
  • @jfriend00 I can see where you're coming from and perhaps it's just best we agree to disagree (or move to a chat page) :-) I would only add two things in reply to your last comment: (1) that the construct given in the question doesn't execute first without being called externally; those parentheses are outside the scope of the function too, they just happen to be *immediately* outside it, and (2) that yes, my example is recursive, as self-execution and self-referentiality are *by definition* recursive. Thanks for an interesting discussion though. – guypursey Jan 14 '13 at 21:54
2

This creates a new empty object:

var module = {};

It does the same as:

var module = new Object();

This wrapper:

(function(exports){
  ...
}(module));

only accomplishes to add an alias for the variable module inside the function. As there is no local variables or functions inside that anonymous function, you could do the same without it:

module.notGlobalFunction = function() {
  console.log('I am not global');
};  

An anonymous function like that could for example be used to create a private variable:

(function(exports){

  var s = 'I am not global';

  exports.notGlobalFunction = function() {
    console.log(s);
  };  

}(module));

Now the method notGlobalFunction added to the module object can access the variable s, but no other code can reach it.

Guffa
  • 666,277
  • 106
  • 705
  • 986
0

"self-executing" might be misleading. It is an anonymous function expression, that is not assigned or or given as an argument to something, but that called. Read here on Immediately-Invoked Function Expression (IIFE).

what is var module = {} doing?

It initializes an empty object that is acting as a namespace.

why is it called again inside the fist function?

It is not "called", and not "inside" the first function. The object is given as an argument ("exports") to the IEFE, and inside there is a property assigned to it.

BenMorel
  • 31,815
  • 47
  • 169
  • 296
Bergi
  • 572,313
  • 128
  • 898
  • 1,281
0

The IIFE is adding a method to the module object that is being passed in as a parameter. The code is demonstrating that functions create scope. Methods with the same name are being added to a object and the the head object (window) of the browser.

DaveB
  • 9,386
  • 4
  • 37
  • 63