J

JavaScript Handbook

Clean • Professional

Anonymous, Callback & Async Functions

3 minute

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.

learn code with durgesh images

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 TypeDescriptionCommon Use Cases
AnonymousFunction without a name, often used inlineCallbacks, one-time logic
Higher-OrderTakes or returns another functionFunctional programming, array methods
CallbackPassed as argument to another functionEvent handling, async code
Async / PromisesHandle asynchronous operationsAPI calls, delays, data fetching
GeneratorPauses and resumes execution using yieldIteration, lazy loading, async control


Article 0 of 0