Self executable functions in javascript

I hate explaining in very big theories like big bang theory 😉

I want to be simple and short always. I will make it clear with what  i understood.

Guys, I understood self exec functions are like some kind of anonymous functions partially. Dont get confuse, my coming to end of this article i promise you will understand the reason why javascript introduces this self executable functions.

Piece of code..

(function(){ console.log(‘Hello World!’); })();

(or)

var helloWold = function() {
	alert('Hello World');
}

 

The above one is self exec function and anonymous function too..

Let’s look at this carefully. This code is made up of two key parts.

First is the anonymous function:

1
2
3
(function(){
  //Normal code goes here
})

The really interesting part is what happens when we add this right at the end:

1
();

Those two little brackets cause everything contained in the preceding parentheses to be executed immediately. What’s useful here is that JavaScript has function level scoping. All variables and functions defined within the anonymous function aren’t available to the code outside of it, effectively using closure to seal itself from the outside world.

(function(){

var foo = 3;

alert(foo);

})();

alert(foo);

will first alert “3” and then throw an error on the next alert because foo is not defined.

Simple words: Its all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of javascript code.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s