Anonymous Functions
Anonymous functions in JavaScript are functions created without a name.
In JavaScript and its many frameworks, they are used prominently as callbacks.
A normal function declaration in JavaScript goes with the function
statement first, followed by a user-given name, followed by a pair of opening/closing parentheses (with comma-separated parameters) and finally the body within a pair of braces
function name() {
console.log('This is a normal function.');
}
But unlike normal function declarations, the user-defined name is omitted after the function
statement for anonymous functions and followed by a pair of parentheses (with comma-separated parameters inside). An anonymous function can be assigned to a variable as
var anonymous = function() {
console.log('This is an anonymous function.');
}
and can be invoked by attaching a pair of opening and closing parentheses (with comma-separated arguments inside) to the assigned variable as
anonymous();
But unlike normal functions, you cannot call them before the declaration.
Anonymous Functions as Callbacks
Anonymous functions can also be passed as arguments to another function. They are then known as callback functions. Below, an anonymous function is passed as an argument to the JavaScript pre-defined function setTimeout()
that prints a message after 1 second
setTimeout(function() {
console.log('This message is printed after 1 second.');
}, 1000);
Anonymous functions are also heavily used in jQuery. For example, the .ready()
method is widely used by passing an anonymous function as
$(document).ready(function(){
// inside an anonymous function
});
Anonymous Functions in Self-Invoking Functions
Inside the first pair of parentheses of a self-invoking function is an anonymous function. The succeeding pair of parentheses is the self-executing part which causes the anonymous function inside the preceding pair to be executed immediately
(function(){
console.log('This is a self-executing anonymous function.');
})();