19

I have read a lot about closures in Javascript What are those braces for?? I read on mozilla.org which says closure should be defined as

(function(){...})();

but on http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html, it says the closure function is

(function(){...}());

What's the difference or the latter one is wrong? what's the purpose of the last ()? Would you put some parameters inside? I am looking for a good reference.

Edit: Moreover, there is an example on Mozilla.org

var makeCounter = function() {
var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  }  
};

why the semicolon is needed for this 'function'? If it needs to be invoked immediately after its declaration, a () should be put before the ending semicolon. But there is not.

jbduzan
  • 1,106
  • 1
  • 14
  • 30
Hoy Cheung
  • 1,552
  • 3
  • 19
  • 36
  • It's not a closure, it's an anonymous function. – zerkms Apr 16 '13 at 09:04
  • 1
    Exact duplicate of [What is the difference between those self-executing anonymous function (aka IIFE) implementation](http://stackoverflow.com/questions/16026909/what-is-the-difference-between-those-self-executing-anonymous-function-aka-iife) – zerkms Apr 16 '13 at 09:05
  • 1
    possible duplicate of [(...()) vs. (...)() in javascript closures](http://stackoverflow.com/questions/8774425/vs-in-javascript-closures) – Quentin Apr 16 '13 at 09:05
  • 1
    It invokes the function. Without it you would just create a function which is never run (and which cannot be run, since you cannot reference it in any way). – Felix Kling Apr 16 '13 at 09:11
  • Nobody has answered the primary question on this page. `(function(){...}());` and `(function(){...})();` are the same. The former is Douglas Crockford's preferred method, but the latter is just as valid. – Chuck Le Butt Jan 23 '17 at 15:12

4 Answers4

23

The syntax

(function(){...})()

is simply an immediately invoked anonymous function. It does not matter how you use your brackets, as the underlying code is a function being declared, and invoked.

Closures are instead used to describe a situation where a function has access to variables declared outside of its scope, accessible via closures

For clarity :

If we have the following function

   function hello() {
      alert("Hello");
   }

We can call the function with the following

hello()

Which invokes the function 'hello'. But if we do not wish to give it a name, but still invoke it, then we can do

(function hello() {
   alert("Hello");
})()

Which will do the exact same as the previous example of calling hello

However, in this scenario there is no point in giving the function the name 'hello', so we can simply remove it:

(function() {
    alert("Hello");
})()

Which is the notation used in your original question.

AlanFoster
  • 8,156
  • 5
  • 35
  • 52
  • I believe so - I am saying both methods of invoking the function expression are the same. And that closures are different to immediately invoked function expressions. Let me know if I misinterpreted the question though :) – AlanFoster Apr 16 '13 at 09:08
  • is there any good documentation about the invocation brackets? – Hoy Cheung Apr 16 '13 at 09:35
  • @user1978421 I have added a gradual example of this for you – AlanFoster Apr 16 '13 at 09:45
8

Your example shows an Immediately Invoked Function Expression, or IIFE. It says to the interpreter:

  • here is a function
  • it has no name
  • keep it away from the global scope ie 'window'
  • call it now

Yes, you can put parameters inside the last (). For example:

(
    function(username){
        alert("Hello " + username);
    }
)("John Smith")

Closures are a feature of javascript that allows us to implement data hiding which is roughly equivalent to private variables in languages like C++ or Java.

function getBmiCalculator(height, weight) {
    // These are private vars
    var height = height;
    var weight = weight;

    function calculateBmi(){
        return weight / (height * height);
    }
    return calculateBmi;
}

var calc = getBmiCalculator(1.85, 90);

// calc still has access to the scope where height and weight live.
var bmi = calc();
alert(bmi);

In this example, height & weight cannot be garbage-collected until calc is destroyed. The section of memory or "scope" where height & weight exist are "Closed Over"

KevSheedy
  • 3,195
  • 4
  • 22
  • 26
3

There is no difference. You can also do so:

true && function(){ /* code */ }();
0,function(){ /* code */ }();

!function(){ /* code */ }(); // Facebook style
~function(){ /* code */ }();
-function(){ /* code */ }();
+function(){ /* code */ }();

// with new    
new function(){ /* code */ }
new function(){ /* code */ }() // if you need arguments then use brackets
Ildar
  • 798
  • 2
  • 14
  • 35
  • 3
    And why is that? This is all correct, but I doubt that a JavaScript beginner will understand why these work. – Felix Kling Apr 16 '13 at 09:17
  • Because you can save 1 character in some cases :) – Ildar Apr 16 '13 at 09:24
  • 4
    That's not what I meant. E.g. why do `(function(){ /* code */ }());` or `+function(){ /* code */ }();` work while `function(){ /* code */ }();` or `*function(){ /* code */ }();` don't? What are the characteristics of these lines that allow the function invocation? – Felix Kling Apr 16 '13 at 09:29
2

the grouping operator can surround the function description as without call parentheses, and also including call parentheses. I.e. both expressions below are correct FE:

      (function () {})();
      (function () {}());

Function Expression

hoogw
  • 4,982
  • 1
  • 37
  • 33