I have been working on JavaScript quite extensively since last few months and I found this self executing function really helpful. It’s unique in its own way and can actually help you a lot. A self executing function in JavaScript is the one which is invoked automatically as soon as it is defined. It’s an anonymous function and is usually used in conjunction to onload event.

Let me show you, how we define a self invoking or self executing function in JavaScript.

<script>
//Example 1
 (function(){
   alert('I am being called');
 })();
 
//Example 2
 (function(x){
   alert(x);
 })('I am passed as an argument');
 
</script>

As you can notice, in the above lines of code, we did not specify name to the function and that is why its called anonymous function. The function is wrapped inside the round brackets and is called as soon as its definition is completed. You can also pass the arguments, if need be, as show in the second example.

Where to use self executing function JavaScript?

It’s nice that you have learnt a new thing in JavaScript, but it is of no fun until you know its real use. So, to be very clear we use these kind of functions when we want variables with limited or local scope. Unclear ? Let’s take a scenario.

You created a nice shiny widget, eg. Twitter updates widget. In this widget, you have used extensive JavaScript functionality to pull new tweets and show some other information. Now this widget code can be embedded on various websites which already have their own JavaScript code. So how can you be sure that the function names which you have used is not being used on end-user’s website ? The variable names which you are using are not in use already ? So to get rid of these uncertainties we use this variant from anonymous functions family.

Hope this helps you to write some nice code. Doubts? I am just a comment away.

Stay Digified !!
Sachin Khosla

Share this post: