Functions created without identifiers or a name for them are called anonymous functions. Functions which are evoked one-time are made anonymous. They are dynamically created and compiled at run time. They can also be self-executing, meaning they can get called themselves without any external object. 

Syntax

function IdentifierOptional(ParameterOptional) { Function body }

Example of an anonymous function

The events to be carried out on loading a page can be made self-executing anonymous function:

Same example from above may be written as:

<html>
<body>
<script>
    var onload = function(){
        alert("You are visiting child only website");
    }    
    onload();
</script>
</body>
</html>

Here onload is a variable to store the returned object. The function(){….} is called a function operator instead of function declaration. Whenever a function operator is called, it calls a new function object and returns it to the variable assigned (like onload in this example).

Anonymous functions are mostly used to be passed as a function parameter or as a closure. They can also be nested, as in example of person() and human.getAge() given below:

Example with nested anonymous functions

The Arguments can be passed to anonymous functions as in normal functions.

Example of passing arguments in anonymous functions

Advantages of using anonymous functions

Anonymous functions have access to all current local variables within scope which simplifies code. They do not have namespace conflict as they do not have name. 

Disadvantages of using anonymous functions

However it is not a good practice to use anonymous functions in loops as it take more run time. Adding event listeners as anonymous functions has the disadvantage of not pulling out one listener only as there is no handler for the function.

 

›› go to examples ››