DEV Community

Lokesh
Lokesh

Posted on

Callback Functions in JavaScript.

What Is a Callback Function?

A callback function is a function that is passed as an argument to another function and can be called inside that function.

In simple words, we give one function to another function so it can execute it when needed.

Let's understand this with a simple example.

1. A Simple Callback Example

function greet() {
    console.log("Hello!");
}

function welcome(callback) {
    callback();
}

welcome(greet);
Enter fullscreen mode Exit fullscreen mode

Output:

Hello!
Enter fullscreen mode Exit fullscreen mode

Let's understand what happens:

  • greet() is a function that prints "Hello!".
  • welcome() accepts a function through its callback parameter.
  • welcome(greet) passes the greet function to welcome.
  • callback() executes the function it received.

Notice that we pass greet without parentheses because we are passing the function itself, not calling it immediately.

2. Callback Functions with Parameters

We can also pass data to a callback function.

function calculate(a, b, callback) {
    let result = a + b;
    callback(result);
}

function display(value) {
    console.log(value);
}

calculate(10, 20, display);
Enter fullscreen mode Exit fullscreen mode

Output:

30
Enter fullscreen mode Exit fullscreen mode

Here, calculate() adds two numbers and passes the result to the display() callback.

This allows us to separate the calculation from displaying the result.

3. Using an Anonymous Callback

We don't always need to create a separate named function for a callback. We can pass an anonymous function directly.

function greet(callback) {
    callback();
}

greet(function() {
    console.log("Welcome to JavaScript!");
});
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome to JavaScript!
Enter fullscreen mode Exit fullscreen mode

The function passed directly to greet() is the callback.

4. Callback Functions with Array Methods

Callbacks are commonly used with JavaScript array methods such as forEach(), map(), and filter().

For example, using forEach():

let fruits = ["Apple", "Banana", "Mango"];

fruits.forEach(function(fruit) {
    console.log(fruit);
});
Enter fullscreen mode Exit fullscreen mode

Output:

Apple
Banana
Mango
Enter fullscreen mode Exit fullscreen mode

Here, the function passed to forEach() is a callback. JavaScript calls it for each element in the array.

Why Are Callback Functions Important?

Callback functions help us:

  • Reuse functions in different situations.
  • Pass behavior from one function to another.
  • Work with array methods.
  • Handle events and delayed operations.
  • Understand asynchronous JavaScript.

Top comments (0)