Last modified on 25 March 2015, at 14:22

JavaScript/Anonymous Functions

Previous: Functions Index Next: Object-Based Programming

Anonymous FunctionsEdit

An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation.

Normal function declarationEdit

function hello() {

Anonymous function declarationEdit

var anon = function() {
  alert('I am anonymous');

The most common use for anonymous functions are as arguments to other functions, or as a closure.

setTimeout(function() {
}, 1000);
// Our anonymous function is passed to setTimeout, which will execute
// the function in 1000 milliseconds.
(function() {
// This is a common method of using an anonymous function as a closure,
// which many JavaScript frameworks use.

Breakdown of the above anonymous statements:

  • the surrounding braces is a wrapper for the anonymous function
  • the trailing braces initiates a call to the function and can contain arguments
(function(message) {
// Another way to write the previous example and get the same result

An alternative representation of the above places the initiating braces to the surrounding braces and not the function itself, which causes confusion over why the surrounding braces are needed in the first place.

(function() {
  // …

Some have even resorted to giving the trailing braces technique derogatory names, in an effort to encourage people to move them back inside of the surrounding braces to where they initiate the function, instead of the surrounding braces.

// returns the factorial of 10.
alert((function(n) {
  return !(n > 1)
  ? 1
  : arguments.callee(n - 1) * n;

The arguments.callee local variable can be used within the function body and refers to the function by itself, which is necessary for recursive anonymous functions.

arguments.callee is deprecated in ECMAScript 5 Strict.

Instead of using arguments.callee, which makes it impossible to achieve tail recursion (a future plan for JavaScript) and also results in a different this value - such issues are resolved by using a named function expression instead.

// returns the factorial of 10.
alert((function factorial(n) {
  return (n <= 1)
  ? 1
  : factorial(n - 1) * n;

Previous: Functions Index Next: Object-Based Programming