Anonymous function is a function without a name. It can be saved to a variable, passed as a parameter, or created for one-time use. Often used in callback functions and functional programming. 🎯
const greet = function() {
return 'Hello!';
};
console.log(greet()); // 'Hello!' ✅Anonymous functions are regular functions but without a name. They are very useful in different situations. Let’s understand why they are needed. 😊
A function without a name that can be used immediately:
// Anonymous function
function() {
return 'Result';
}const greet = function() {
return 'Hello!';
};
console.log(greet()); // 'Hello!' ✅// Anonymous function as callback
setTimeout(function() {
console.log('One second passed');
}, 1000);const numbers = [1, 2, 3, 4, 5];
// Anonymous function to process each element
const doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6, 8, 10] ✅// Anonymous function as click handler
button.addEventListener('click', function() {
console.log('Button clicked');
});// Named function
function namedFunction() { }
// Anonymous function
const anonymous = function() { };
// It has no name!// Can be used immediately when calling
[1, 2, 3].forEach(function(item) {
console.log(item); // 1, 2, 3
});// Asynchronous operation
fetch('/api/data').then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
});// Filtering array
const adults = users.filter(function(user) {
return user.age >= 18;
});// ❌ This is not allowed — syntax error
// function() { console.log('Error!'); }();
// ✅ Need to assign to variable or call immediately
const func = function() { console.log('Correct!'); };
func(); // ✅
// Or call immediately
(function() { console.log('Immediately!'); })(); // ✅// ❌ Named function
function sum(a, b) { return a + b; }
// ✅ Anonymous function
const sum = function(a, b) { return a + b; };Anonymous functions are a convenient tool for different tasks. They make code more flexible and simpler. 👍
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪