In JavaScript, an anonymous function is a function that is declared without a name. These functions are often used for short tasks or as arguments for other functions, such as callbacks.
Syntax of Anonymous Functions
An anonymous function is often defined using the function
keyword, but without a name, like this:
function() {
console.log("This is an anonymous function");
}
However, anonymous functions are typically used in assignments or as arguments, like this:
1. Anonymous Function Assigned to a Variable
let greet = function() {
console.log("Hello, World!");
};
greet(); // Calls the anonymous function
In this example, the anonymous function is assigned to the variable greet
, and then we can call it like a regular function.
2. Anonymous Functions as Arguments (Callbacks)
Anonymous functions are commonly used as callbacks, which are functions passed as arguments to other functions.
setTimeout(function() {
console.log("This will be executed after 2 seconds.");
}, 2000);
In this example, the anonymous function is passed as the callback to setTimeout
, and it gets executed after the specified delay.
3. Anonymous Functions in Array Methods
Anonymous functions are often used in array methods like map()
, filter()
, and forEach()
.
let numbers = [1, 2, 3, 4];
numbers.forEach(function(num) {
console.log(num * 2); // Doubles each number in the array
});
Here, the anonymous function is passed to forEach()
, and it operates on each element of the numbers
array.
4. Immediately Invoked Function Expression (IIFE)
An anonymous function can also be executed immediately after it is defined. This is called an IIFE (Immediately Invoked Function Expression).
(function() {
console.log("This function is executed immediately!");
})();
In this case, the anonymous function is wrapped in parentheses, and then ()
at the end invokes it immediately.
5. Arrow Functions (ES6)
In ES6 (ECMAScript 2015), arrow functions provide a more concise syntax for anonymous functions. Arrow functions are always anonymous.
let greet = () => {
console.log("Hello from arrow function!");
};
greet(); // Calls the anonymous arrow function
Arrow functions can also take parameters and return values more concisely:
let sum = (a, b) => a + b;
console.log(sum(2, 3)); // Outputs 5
Summary of Anonymous Functions:
- Anonymous functions do not have a name.
- They are often used for callbacks or short-lived tasks.
- They can be stored in variables, passed as arguments, or executed immediately (IIFE).
- Arrow functions provide a shorter syntax for writing anonymous functions.
These functions are widely used in JavaScript for handling events, performing asynchronous tasks, and in functional programming techniques like map()
, filter()
, and reduce()
.