Self-invoking functions explained line by line

I never knew it was possible to love a syntax but since, I fell in love with the self-invoking function which can be summarized like this : (function(){})(). Yes this is a valid syntax though it doesn’t do much in this form (it creates a function that does nothing and call it).

Some people call it self-invocation or self-executing but I don’t think it has an official name.

Let’s break it down

It will become clearer if I execute some code and write it on more than one line :

  1. (
  2.   function() {
  3.     console.log("this line is called");
  4.   }
  5. )
  6. ();

Line 1 : (
This first parenthesis is used as grouping operator. Read more here and here.

Line 2 : function() {
This create an anonymous function. I could write something like function doSomething() { but in the case of a self-invoking function, this is useless because the function is in its own little scope (line 1) and can’t be called from outside of it.

Line 3 : console.log(“this line is called”);
This is the code that will be invoked.

Line 4 : }
This clauses the function opened at line 2.

Line 5 : )
Clauses the parens opened at line 1.

Line 6 : ();
We call the function created at line 2 and returned within the scope from line 1 to 4.

Let’s write it in a more compact syntax :

  1. (function() {
  2.   console.log("this line is called");
  3. })()

See my post about using self-invoking functions to create namespaces.

Don’t forget to subscribe to my newsletter!

  • bkqc

    I’m not totally sure but I think It is not totally true to say that it is not necessary to write the function name simply because it is out of scope since this name will be shown in the stack trace.

  • http://www.javascriptkata.com dsimard

    Yeah, it is recommended to always name your functions, even if they are “anonymous” because of the stack trace.

  • Tom_here

    i name it this way:
    (thisFunction=function(){})()

  • http://www.javascriptkata.com dsimard

    The problem is that it creates a global variable. If you use that technique often on the same project, you could create a mess.

    If you want a self-invoking function that can be called later, I suggest to use a named function and return it. Like this :

    var outOfScope = (function inScope(){console.log(“test”);return inScope;})();

    Then, you can use the function outOfScope() anywhere in your code.

  • venkman

    > Some people call it self-invocation or self-executing but I don’t think it has an official name.

    This link http://benalman.com/news/2010/11/immediately-invoked-function-expression/ may provide an alternative perspective on this.

  • TimTheTinker

    Line 1: actually, the immediate invocation of the function declaration makes the whole thing a statement. You need a semicolon at the end. (And at the end of the console.log line). Semicolons are essential in Javascript to avoid ambiguity (since the interpreter will insert them anyway, and not necessarily where the reader might expect).

  • http://www.javascriptkata.com dsimard

    I added the semicolons everywhere they were needed, I normally always write them and I don’t know why I didn’t stick to that on that post.

    For the parens, I’ll have to look into it a little more. I updated the post without the explanation on what it does and I’ll re-update later when I’ll find the correct answer.

  • http://www.javascriptkata.com/2011/09/05/creating-namespaces-with-self-invoking-functions/ Creating namespaces with self-invoking functions » Javascript Kata

    [...] Now, I only have to write c.list because c is an alias of the Animal.Cat namespace. Thanks to self-invocation! [...]

  • http://www.javascriptkata.com/2011/09/13/how-to-make-sure-undefined-is-not-defined/ How to make sure undefined is not defined » JavascriptKata

    [...] There’s two way of redefining undefined and they both use self-invoking functions. [...]

  • http://thuld.wordpress.com/2011/12/20/dynamics-crm-coding-conventions/ Dynamics CRM Coding Conventions « thuld

    [...] das der global Namespace  unnötiger Weise mit variablen belastet wird. Verwendet man jedoch den Ansatz der „self-invoking function“ kann man diese Problem umgehen. Stark vereinfacht gesagt [...]

  • http://thuld.wordpress.com/2011/12/20/dynamics-crm-coding-conventions-2/ Dynamics CRM Coding Conventions « thuld

    [...] das der global Namespace unnötiger Weise mit variablen belastet wird. Verwendet man jedoch den Ansatz der „self-invoking function“ kann man diese Problem umgehen. Stark vereinfacht gesagt [...]