< JavaScript

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 parentheses are a wrapper for the anonymous function
  • The trailing parentheses initiate 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[1] 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) );

An arrow function expression is similar to what in other programming languages is known as lambda, introduced in ECMAScript 6 in 2015. It provides a shorthand for creating anonymous functions.

Examples:

  • x => x + 1
    • An anonymous function with one argument x that returns x + 1.
  • x => {return x + 1}
    • As above, but with a function body.
  • (x, y) => x + y
    • A 2-arg arrow function.
  • (x, y) => {return x + y}

Links:

  1. https://www.geeksforgeeks.org/recursive-functions/
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.