In this article, I will discuss self-executing or self-invoking functions of javascript and their hidden power with real-world example. We will also see why using setInterval is bad in some situations and should be avoided. Let’s explore little used but extremely powerful self-invoking functions of javascript.
Self-Invoking Anonymous Function
A self-invoking anonymous runs automatically/immediately when you create it and has no name, hence called anonymous. Here is the format of self-executing anonymous function:
(function(){ // some code… })();
You must be aware of the fact that javascript functions run immediately when you put () after their names eg:
doStuff(); // this will run immediately
And:
doStuff; // this will not run immediately and can be used as callback
Now because () exist at the end of self-executing anonymous function above, it will run immediately.
Interestingly, if you look at the source code of jQuery, you will see that everything is wrapped in between:
(function( window, undefined ) { // jQuery code })(window);
That is as can be seen also a self-executing anonymous function with arguments. A window (and undefined) argument is created and is mapped with global window object at the bottom (window).
Notice that you can also write self-executing anonymous function like this:
(function(){ // some code… })();
Using extra braces like before function keyword is simply coding convention and is used even by famous javascript libraries such as jQuery and also recommended by Douglas Crockford. If you are confused about that extra pair of braces, here is another easy to remember notation:
! function(){ // some code… }();
An ExpressionStatement cannot start with thefunction
keyword because that might make it ambiguous with a FunctionDeclaration.
Self-Executing Function
Self-Executing function is a named function that runs immediately. Example:
(function foo(){ // some code… })()
Notice that now that we have named our function foo, it is not an anonymous function though it still is self-executing function because of () at the end.
How do they run automatically?
This can be best explained through an example. Let’s say in your webpage you have this javascript code:
function showUp(){ alert(’Hello There’); }
When you visit the page, the showUp function will not get triggered unless you do so by calling the function:
function showUp(){ alert(’Hello There’); } // run the function showUp();
However, you can make the function auto-run by making it self-executing function like this:
(function showUp(){ alert(’Hello There’); })()
Where to use self-executing functions?
One obvious situation is when you want to auto-run a function like I showed in above example but that is trivial. If you are in a situation where you want to run a piece of code repeatedly like updating something in the database based on user interaction or fetching records from database every 10 seconds or you want to load new stories via ajax similar to how facebook does on its homepage or some other similar situation, one would normally go for setInterval function something like this:
setInterval(doStuff, 10000);
Above, doStuff function will get called every 10 seconds. That is the normal approach most developers seem to go with. However, there is a huge problem with that. The setInterval will call doStuff function exactly at specified time of 10 seconds again and again irrespective of whether doStuff function actually finished doing what it is supposed to do. That is bad and will certainly get you into unexpected results.
That is one example of where setInterval is ^bad^ and should be avoided.
This is exactly where self-executing functions come in handy. We can do the same task with the help of self-executing function along with setTimeout like this:
! function foo(){ // your other code here setTimeout(foo, 10000); }();
This code will also repeat itself again and again with one difference. setTimeout will never get triggered unless doStuff is finished. A much better approach than using setInterval in this situation.
You can see the example in action here.
Another more common use of self-invoking functions is data privacy, everything wrapped in them is only available within the scope of these functions.
Nice article, thak you!
Very amazing and very clear article..Thanks Sarfraz Ahmed Sir.. 🙂
You are welcome
Thank you, I had been searching for this function explanation for a long time
Pingback: Dynamic script paths in Require.js | Beans & Curry
simple and clear.
One caveat… If you want to do stuff on a timer (e.g. update a clock display every 10 seconds) you need to use setInterval() because setTimeout() will not be accurate. It will count to 10 seconds after execution.
You could still pass doStuff as a callback to setInterval — if doStuff has a flag that checks for previous execution completion. But you’re right — in most cases, setTimeout() is what you want to do. Just be aware that you’re waiting 10 seconds after executing, not executing every 10 seconds.
Very enlightening, thank you!
Clears up many questions I had but was too clueless to ask – thanks!!!
function showUp(){
alert(’Hello There’);
}()
SyntaxError: Unexpected token )
Work this code:
(function showUp(){
alert(’Hello There’);
})();
or this:
(function showUp(){
alert(’Hello There’);
}());
The self invoking named function needs a bracket at the beginning like this: (someFunction function(){ // some stuff here })();
Your example is missing it.
Finally, a clear explanation. Thanks a lot.
Thanks everyone for pointing out that I was missing grouping operator, updated the example code now. Thaniks
Here <>; didn’t you mean foo & not doStuff?
setTimeout will never get triggered unless doStuff is finished.
Nice example
Very nicely explained, Thank you!! favs for you
In fact, there is command evaluation in those structures
you may test
! function(param) { alert(param); } ( );
That autostarts, but what about the ( ) ???
Well, in fact is a call to a retro param
! function(param) { alert(param); } ( ‘Hi’ );
Now the function will alert “Hi” at autostart
What can be passed? any param, object, string, number, etc. an any number of params
The fact is that used there are as initializers, since they will be used just once.
Pingback: JavaScript Self-Invoking Functions(); ;) | Geek Girl Arises
best explanation gj!
very helpful. thanx.
Just a note on your choice of words “self invoking” is a legacy term and misleading description for what would be more accurately called an “immediately invoked” function. A self invoking (in other words a recursive function) calls itself within it’s own body, whereas this is simply a function expression that the interpreter executes following it’s definition. See: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Hi agreed and thanks for the clarification 🙂
Pingback: Object-oriented JavaScript | Nexcius.net
Note that the mentioned techniques are slight different. The complete expressions also have a result by themselves. These results are different, espacially if the functions return a value.
(function() { return 1+2; }) () // is evaluated to 3
(function() { return 1+2; }() ) // is evaluated to 3, too
! function { return 1+2; } () // is evaluated to false
void function { return 1+2; } () // is evaluated to undefined
Since many years in most cases I use the last technique, because the void operator does exactly what I want: execute the function and return nothing.
Sorry, there was a mistake in my post. I forgot the parenthesis. It must be:
(function() { return 1+2; }) () // is evaluated to 3
(function() { return 1+2; }() ) // is evaluated to 3, too
! function() { return 1+2; } () // is evaluated to false
void function() { return 1+2; } () // is evaluated to undefined
Thanks a lot!
thanks for the educative piece of information..am glad.its a good work you are doing..from kenya.
Reblogged this on Tushar's Blog – BETA.
Pingback: Javascript Self Invoking Functions | Tushar's Blog - BETA
Pingback: Javascript Self Invoking Functions | Tushar's Blog
Good work : )
Wow! Thank you for clearing up a frustrating road block on my way to learning js.
thanks a lot, very clear
Reblogged this on tahsinabrar.