What is an anonymous function?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Easy
#JavaScript #Functions #JS Basics

Brief Answer

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!' ✅

Full Answer

Anonymous functions are regular functions but without a name. They are very useful in different situations. Let’s understand why they are needed. 😊

What is an Anonymous Function

A function without a name that can be used immediately:

// Anonymous function
function() {
  return 'Result';
}

How to Create an Anonymous Function

Assignment to Variable

const greet = function() {
  return 'Hello!';
};
 
console.log(greet()); // 'Hello!' ✅

Passing as Parameter

// Anonymous function as callback
setTimeout(function() {
  console.log('One second passed');
}, 1000);

Simple Examples

Usage in Arrays

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] ✅

Event Handlers

// Anonymous function as click handler
button.addEventListener('click', function() {
  console.log('Button clicked');
});

Important Features

1. No Name

// Named function
function namedFunction() { }
 
// Anonymous function
const anonymous = function() { };
// It has no name!

2. Flexibility

// Can be used immediately when calling
[1, 2, 3].forEach(function(item) {
  console.log(item); // 1, 2, 3
});

Where Anonymous Functions Are Used

Callback Functions

// Asynchronous operation
fetch('/api/data').then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
});

Higher-Order Functions

// Filtering array
const adults = users.filter(function(user) {
  return user.age >= 18;
});

Common Mistakes

1. Attempting Call Without Assignment

// ❌ 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!'); })(); // ✅

2. Confusion with Named Functions

// ❌ Named function
function sum(a, b) { return a + b; }
 
// ✅ Anonymous function
const sum = function(a, b) { return a + b; };

Simple Rules

  1. No name — anonymous function has no name 🏷️
  2. Flexibility — can be passed as parameters and values 🔄
  3. Callback — often used as callback functions 📞
  4. One-time — convenient for one-time use 🚀
  5. Storage — need to save to variable for reuse 💾

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 💪