JavaScript Anonymous Functions

An anonymous function is a function that has no name, hence can’t be called using its name. Anonymous function is assigned and associated with a variable since, in JavaScript, variables can be of type function.

An anonymous function is stored in a variable using an expression defining the function body. The variable holding a function is used as a function name

	var x = function (a, b) {return a * b}; 

After an anonymous function is stored inside variable, a variable holding a function can be used as normal function call.

<!DOCTYPE html>
<html>
<body>

<p>This example calls a function which performs a calculation, and returns the result:</p>

<p id="demo"></p>

<script>
	var multiply = function (a, b) {return a * b};
	var ans = multiply(25, 7);
document.getElementById("demo").innerHTML = ans;
</script>

</body>
</html>

Download the code Run the code

Advantages of Anonymous functions

  • Anonymous functions can be passed as arguments to other functions
  • Recursions and closures are often use Anonymous functions
  • Anonymous function can be used for scope management as its assigned to variables
  • jQuery JavaScript library heavily based on Anonymous functions
  • Anonymous functions gets defined at run-time

Any normal function can be converted to anonymous function with only minor changes.

Normal Function

// calculates square of given number
function calculateSquare(num) {
    return num * num;
}

Anonymous Function

var calculateSquare = function(num) {return num * num;}

Another version of anonymous function

(function() {
    return num * num;
})

Adding a brackets () at the end of above anonymous function will make it self executing

(function() {
    return num * num;
}) ();
<<< JavaScript FunctionsJavaScript Callback Functions >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .