Function Types in JavaScript
JavaScript supports several types of functions based on how they are defined, used, and executed. Understanding these types is essential for writing clean, reusable, and asynchronous code.
Functions can be anonymous, higher-order, callbacks, asynchronous (Promises/async-await), or even generators that pause and resume execution.
1. Anonymous Functions
An anonymous function is a function without a name.
These functions are usually assigned to variables, used as arguments, or passed as callbacks.
Anonymous functions are ideal when the function logic is simple and used only once.
Example:
const greet = function() {
console.log("Hello, World!");
};
greet(); // Output: Hello, World!
They are often used inside methods like map()
, filter()
, or event handlers.
Example in Callback:
setTimeout(function() {
console.log("Executed after 2 seconds");
}, 2000);
2. Higher-Order Functions
A Higher-Order Function (HOF) is a function that takes another function as an argument or returns a function.
This concept is central to functional programming in JavaScript and enables powerful patterns like callbacks, currying, and composition.
Example:
function higherOrder(fn) {
console.log("Executing higher-order function");
fn(); // calling the passed function
}
function sayHello() {
console.log("Hello from callback!");
}
higherOrder(sayHello);
Real-World Use (Array Methods):
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]
3. Callback Functions
A callback function is a function passed as an argument to another function, which is then executed later.
Callbacks are a way to ensure certain code runs after something else finishes — like an event or asynchronous operation.
Example:
function fetchData(callback) {
console.log("Fetching data...");
setTimeout(() => {
console.log("Data fetched!");
callback(); // Execute the callback after data is fetched
}, 2000);
}
fetchData(() => console.log("Processing data..."));
Types of Callbacks:
- Synchronous Callbacks: Executed immediately (e.g., inside
forEach
). - Asynchronous Callbacks: Executed after a delay or async operation (e.g.,
setTimeout
,fetch
).
4. Async Functions and Promises
Async functions simplify writing asynchronous code in JavaScript using the async
and await
keywords.
They work on top of Promises, which represent a value that will be resolved (fulfilled or rejected) in the future.
Promises Example:
const fetchUser = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("User data fetched successfully!");
}, 2000);
});
};
fetchUser().then(response => console.log(response));
Async / Await Example:
async function getUser() {
console.log("Fetching user...");
const result = await fetchUser();
console.log(result);
}
getUser();
5. Generator Functions
A Generator Function is a special type of function that can pause and resume its execution.
It’s defined using the function*
syntax and uses the yield
keyword to return values one at a time.
Generators are useful for lazy evaluation, iterating large data sets, or controlling async flows.
Example:
function* countNumbers() {
yield 1;
yield 2;
yield 3;
}
const counter = countNumbers();
console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
console.log(counter.next().value); // 3
Advanced Example (Infinite Generator):
function* infiniteCounter() {
let i = 0;
while (true) {
yield i++;
}
}
const counter2 = infiniteCounter();
console.log(counter2.next().value); // 0
console.log(counter2.next().value); // 1
Summary Table
Function Type | Description | Common Use Cases |
---|---|---|
Anonymous | Function without a name, often used inline | Callbacks, one-time logic |
Higher-Order | Takes or returns another function | Functional programming, array methods |
Callback | Passed as argument to another function | Event handling, async code |
Async / Promises | Handle asynchronous operations | API calls, delays, data fetching |
Generator | Pauses and resumes execution using yield | Iteration, lazy loading, async control |