Anonymous Functions in JavaScript
Anonymous functions are those functions that do not have any name. Just like an anonymous call or anonymous email has no identity, similarly, these functions also don’t have a defined name.
What is an Anonymous Function?
An anonymous function is a function without a name, and it is usually stored inside a variable.
Example:
const add = function(a, b) {
return a + b;
}
Here:
- The function has no name
- It is assigned to a variable
add
Calling the Function:
console.log(add(2, 2)); // Output: 4
Anonymous Function vs Function Expression
- Both are stored in variables
- The difference is:
- Function Expression can have a name
- Anonymous Function has no name
Where Do We Use Anonymous Functions?
Anonymous functions are mostly used as callback functions.
Example:
function operations(fun) {
let x = 10;
let y = 20;
console.log(fun(x, y));
}
const add = function(a, b) {
return a + b;
}
const sub = function(a, b) {
return a - b;
}
operations(add); // 30
operations(sub); // -10
Here:
operationsis taking a function as a parameteraddandsubare passed as arguments- These act as callback functions
Another Example: setTimeout
const onTime = function() {
console.log("on time called");
}
setTimeout(onTime, 2000);
setTimeouttakes a function as a parameter- That function is executed after a delay
Hoisting in Anonymous Functions
Anonymous functions behave like function expressions.
- You cannot call them before declaration
add(); // Error
const add = function(a, b) {
return a + b;
}
Difference: Named Function vs Anonymous Function
- Named functions can be called inside themselves (useful in recursion)
- Anonymous functions cannot be called internally because they don’t have a name
- Debugging is easier with named functions
- Anonymous functions are commonly used in callbacks