JavaScript/Anonymous functions

< JavaScript(Redirected from JavaScript/Anonymous Functions)
Previous: Functions Index Next: Object-based programming

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 definition:

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

Anonymous function definition:

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

One common use for anonymous functions is as arguments to other functions. Another common use is as a closure, for which see also the Closures chapter.

Use as an argument to other functions:

setTimeout(function() {
  alert('hello');
}, 1000);

Above, the anonymous function is passed to setTimeout, which will execute the function in 1000 milliseconds.

Use as a closure:

(function() {
  alert('foo');
})();

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

Another way to write the previous example and get the same result:

(function(message) {
  alert(message);
}('foo'));

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.

An anonymous function can refer to itself via arguments.callee local variable, useful for recursive anonymous functions:

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

However, arguments.callee is deprecated in ECMAScript 5 Strict. The issues with arguments.callee are that it makes it impossible to achieve tail recursion (a future plan for JavaScript), and results in a different this value. Instead of using arguments.callee, you can use named function expression instead:

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

External linksEdit

Previous: Functions Index Next: Object-based programming