An anonymous function is a function without a name, mainly used for specific or short-term tasks, and is often assigned to variables or passed as arguments where reuse is not required.
- It omits the function name and is defined using the function keyword or arrow syntax.
- It is commonly used as callbacks or for one-time execution within a limited scope.
let greet = function() {
console.log("Hello!");
};
greet();
Syntax:
The below-enlightened syntax illustrates the declaration of an anonymous function using the normal declaration:
function() { // Function Body }We may also declare an anonymous function using the arrow function technique which is shown below:
( () => { // Function Body...} )();Note: You'll get a syntax error if you don't use parentheses (). The parentheses are needed to treat the anonymous function as an expression, which returns a function object.
[Example 1]: An anonymous function is defined to print a message, stored in the greet variable, and executed by calling greet().
const greet = function () {
console.log("Welcome to GeeksforGeeks!");
};
greet();
[Example 2] : Passing arguments to the anonymous function.
const greet = function( str ) {
console.log("Welcome to ", str);
};
greet("GeeksforGeeks!");
As JavaScript supports Higher-Order Functions, we can also pass anonymous functions as parameters into another function.
[Example 3]: Passing an anonymous function as a callback function to the setTimeout() method. This executes this anonymous function 2000ms later.
setTimeout(function () {
console.log("Welcome to GeeksforGeeks!");
}, 2000);
Self-Executing Anonymous Functions
Another common use of anonymous functions is to create self-executing functions (also known as IIFE - Immediately Invoked Function Expressions). These functions run immediately after they are defined.
[Example]: Creating a self-executing function.
(function () {
console.log("Welcome to GeeksforGeeks!");
})();
Arrow functions
Arrow Functions are a shorter ES6 syntax for writing anonymous functions, where the function keyword is not required and => is used to define the function.
- They provide a more concise and readable syntax.
- Commonly used for callbacks and short function expressions.
[Example 1] : This is an example of anonymous function with arrow function.
const greet = () => {
console.log("Welcome to GeeksforGeeks!");
}
greet();
- If an arrow function has only one statement, curly braces {} can be omitted.
- The result of that statement is returned automatically without using return.
[Example 2]: A simple arrow function with a single expression is used.
const greet = () => console.log("Welcome to GeeksforGeeks!");
greet();
[Example 3]: lllustrates a self-executing function (IIFE), which immediately invokes itself after being defined
(() => {
console.log("GeeksforGeeks");
})();