Anonymous Method in JS

What are anonymous methods?

Anonymous methods are the methods which have no name. As they have no name so they can only be called at the time of their definition.

Example of an anonymous function:

function(){
   //do something
}();

The above method is anonymous method and we can call it once. Also we can pass parameters inside it as you can see in the following example.

function(message){
   alert(message);
}('hello world');

Now, whats the benefit of anonymous function? Benefit of anonymous function is to restrict its calling multiple times. So, we can just call it once the page is refreshed or loaded. Hence we can do stuff which is required only once in the page like some initialization of variables or loading of scripts.

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