Self-executing functions

Update: "Immediate functions" sounds like a much better name.

Self-executable functions are simple and powerful.

All you do is add a set of parentheses after the function and this causes it to be executed right there. If it’s an anonymous function you also need to wrap it in parentheses.

(function(){
   var a = 1;
   var b = 2;
   alert(a + b);
})();

You can also pass parameters to the self-executing function if you want.

(function(a, b){
  var c = a + b;
  alert(c);
})(1, 2);

So how is this pattern useful?

It’s useful when you have some work to do, some initialization maybe. You need to do it only once and you don’t want to leave any globals lying around after the work is finished. All the temporary variables you need like c in the case above remain local and don't pollute the namespace.

Useful also when your code is kind of a guest to the page. Like a bookmarklet for example, or a widget of some sorts. You don’t want to add your variables and functions to the host page’s naming space and possibly causing a naming conflict with the page's core code.

Tags: , ,

20 Responses to “Self-executing functions”

  1. Alva Giannecchini Says:

    awesome bless you for composing this

  2. Avi Says:

    I didn’t understand the part of:
    “…You don’t want to add your variables and functions to the host page’s naming space and possibly causing a naming conflict with the page’s core code.”
    How can this scenario happen?
    Can you give me an example?

  3. Karl Says:

    @Avi – I think the author is trying to get across that the variables and functions inside a self-executing anon function will not be global and therefore won’t clobber any variables / functions that may already exist in the global namespace, i.e. if you declare a var / function without namespacing it or using a particular function pattern it will be part of the global namespace, i.e. the window object in a browser, hope this helps….

  4. Justin Says:

    I’m using this method exactly in the bookmarklet I created. Works perfect!

  5. Spencer Drager Says:

    @Avi – There are plenty of examples. How often do you name variables something common?

    Perhaps you use a single letter for a quick toggle value or whatnot, so you make a var i, var x, or var o. If these are in the global namespace, it would not be uncommon for another function to use the same name which can cause some interesting bugs. Or what if you name something like “isComplete” or “isReady” or any number of other generic, yet descriptive, names? By putting these in a self-executing function to reduce the likelihood of causing conflicts.

  6. pellet mill automation Says:

    We really enjoy your site publish. You can find truly lots of procedures we could place it to good use by the use of no work soon enough and economic assets. Thanks a great deal pertaining to supporting make this submit give light to quite a few troubles now we have encountered before now.

  7. » Pseudoklassische Vererbung in JavaScript – Teil 4 The Codejet Says:

    [...] (engl. function expression) zugewiesen, der sofort ausgeführt wird. Dies wird auch als "immediate function" bezeichnet. Rückgabewert ist dabei ein weiterer anonymer Funktionsausdruck, der bis auf ein Detail [...]

  8. Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope | JavaScript Mountain Says:

    [...] http://www.jspatterns.com/self-executing-functions/ [...]

  9. Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope | Acme Travel Says:

    [...] http://www.jspatterns.com/self-executing-functions/ [...]

  10. Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope | Kevin Chisholm Blog Says:

    [...] http://www.jspatterns.com/self-executing-functions/ [...]

  11. dev 4 WP testing - Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope Says:

    [...] http://www.jspatterns.com/self-executing-functions/ [...]

  12. Kevin Chisholm – Blog - Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope Says:

    [...] http://www.jspatterns.com/self-executing-functions/ [...]

  13. Edwin Yip | dev of LIVEditor Says:

    Thanks! Your posts archived under the “functions” category is really helpful to me who’s coming from a Delphi (Object Pascal) background.

  14. daszki nad drzwi Says:

    The company serves the entire area surrounding Ontario and the greater Quebec area.
    There are two different types of roofs which are used
    on all the buildings that him and i see around us: business and residential.
    Their contractor will be happy to show them some samples of each
    of their options, and give them the pros and cons to each type of material.

  15. feng shui design Says:

    You could possibly unquestionably call at your experience in the works of art you are submitting. The whole world desires all the more enthusiastic freelancers as if you that aren’t scared to cover how they imagine. All the time focus on the coronary heart.

  16. cheap bulk candy Says:

    Way cool! Some extremely valid points! I appreciate you writing this write-up and the
    rest of the site is very good.

  17. drzwi drewniane Says:

    Excellent weblog right here! Also your site so much up fast! What host are you the use of? Can I am getting your affiliate hyperlink for your host? I desire my website loaded up as quickly as yours lol

  18. MupKequeDus Says:

    内側お気軽にお申し付けくださいませ。ファスナー付きポケット,トリーバーチ バッグ ナイロン、.
    その旨考慮しての価格になっております。さらには食べ物を保存するに使用されるために使用されます。それらは大きく、マルチカラー内側:.
    縦17cm横2431cmまち11cm 持ち手 32cm ストラップ 60cm(取外し可能) [url=http://www.gagasekai.com/c-124.html]ガガミラノ ダイビング 通販サイト[/url]
    シャネル クラシックバッグ ∥ コーチショルダーバッグ激安 A 48in .メッセージボードが本当に、楽しかったです」とニッコリ。!
    コーチCOACHバッグ COACHコーチのシグネチャー2wayバッグ シグネチャーとエナメルレザー製 ボストンタイプのトートバッグ、約1.0〜2.5cm素材キャンバスカラーブラウン系※色に関してはこの商品の出品者の主観で判断しておりますので、◇COACH◇水や汚れに強いPVC素材を使用した、!

  19. Slallireimmek Says:

    [url=www.netagura.com/]www.netagura.com/[/url]
    http://www.mesapatent.com/
    [url=http://www.netagura.com/]Michael Kors factory outlet[/url]
    [url=http://www.mesapatent.com/]michael kors shoulder bags outlet[/url]
    Do you want to find the Michael Kors wiht big discount?Our Michael Kors Satchels online store have cheap Michael Kors Satchels outlet,Michael Kors Satchels big discount.
    [img]http://www.netagura.com/includes/templates/netagura/images/brand/top03.jpg[/img]

  20. personalized invitations Says:

    My coder is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the costs. But he’s tryiong none the less. I’ve been using Movable-type on a number of websites for about a year and am worried about switching to another platform. I have heard excellent things about blogengine.net. Is there a way I can import all my wordpress content into it? Any kind of help would be really appreciated!

Leave a Reply