Callback Functions
A Callback Function is a function that is passed as an argument to another function and is executed later when it is needed.
A callback function is passed to another function and executed when required.
Simple Explanation
Think of a Callback Function like giving someone
a task to perform after another task is completed.
In JavaScript, we can pass a function as an argument
to another function. The receiving function can then
call that function when it needs to.
The function passed as an argument is called a
Callback Function.
Basic Syntax
The basic idea is:
Main Function → Callback Function → Result
A callback is passed as an argument and called
inside the main function.
Parts of a Callback Function
This is the function that receives another function as an argument.
This function is passed as an argument and executed by the main function.
The callback is called inside the main function when it is required.
Callback Function Flow
processData()
displayResult()
callback()
Result
Example 1: Simple Callback Function
Here, one function is passed to another function as an argument.
function greet(name, callback) {
console.log("Welcome to " + name);
callback();
}
function instituteMessage() {
console.log("CIIT Training Institute");
}
greet("CIIT Training Institute", instituteMessage);
Welcome to CIIT Training Institute
CIIT Training Institute
Example 2: Callback with Arrow Function
An Arrow Function can also be directly passed as a callback.
function displayInstitute(callback) {
callback();
}
displayInstitute(() => {
console.log("CIIT Training Institute");
});
CIIT Training Institute
Example 3: Callback with Data
A callback can also receive data from the main function.
function getInstituteName(callback) {
const institute = "CIIT Training Institute";
callback(institute);
}
function showInstitute(name) {
console.log("Institute:", name);
}
getInstituteName(showInstitute);
Institute: CIIT Training Institute
Example 4: Callback After a Task
A callback can be executed after the main function completes its task.
function completeTraining(callback) {
console.log("Training Completed");
callback();
}
completeTraining(() => {
console.log("Welcome to CIIT Training Institute");
});
Training Completed
Welcome to CIIT Training Institute
A Callback Function is passed as an argument to
another function. It runs only when the receiving
function calls it.
Passing the function:
completeTraining(message)
Calling the callback:
callback()
Summary
A Callback Function is a function passed as an argument to another function. The receiving function can execute the callback when required. Callbacks allow one function to perform another action after completing its work and are commonly used in JavaScript programming.