DEV Community

sai sanjana
sai sanjana

Posted on

what is call back function?

hi all,
A callback function is an important concept in JavaScript. It is a function that is passed as an argument to another function and is executed later. Callback functions help make code more flexible and are commonly used for handling events, processing data, and performing asynchronous operations.

What is a Callback Function?

A callback function is simply a function that is given to another function to be called when a specific task is completed.

Example
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}

function sayGoodbye() {
console.log("Goodbye!");
}

greet("John", sayGoodbye);
Output
Hello, John
Goodbye!

In this example, sayGoodbye is the callback function.

Why Use Callback Functions?

Callback functions are useful because they:

Make code reusable.
Allow functions to perform different actions.
Help handle asynchronous tasks.
Improve flexibility in programming.

They are widely used in modern JavaScript applications.

Callback Functions with Array Methods

Many JavaScript array methods use callback functions.

Example with forEach()
let numbers = [1, 2, 3];

numbers.forEach(function(number) {
console.log(number);
});
Output
1
2
3

The function inside forEach() is a callback function that runs for each array element.

Callback Functions and Events

Callbacks are often used to respond to user actions such as button clicks.

Example
button.addEventListener("click", function() {
console.log("Button clicked!");
});

When the button is clicked, the callback function is executed.

Advantages of Callback Functions
Increase code flexibility.
Support asynchronous programming.
Allow functions to be reused in different situations.
Simplify event handling.

These benefits make callbacks a fundamental part of JavaScript.

Top comments (0)