Callback Function Explained - Private Scope in JS
A callback function is a function that is passed as an argument to another function and is executed later.
Definition:
A callback function is:
- Passed inside another function
- Executed inside that function when needed
Basic Example
function greet(name, callback) {
console.log("Hello", name);
callback(name);
}
greet("Anil", function(userName) {
console.log("Good Bye", userName);
});
Output:
Hello Anil
Good Bye Anil
Explanation:
greetfunction takes a function as a parameter- That function becomes the callback
- It is executed inside
greet
Passing Parameters in Callback
function greet(name, callback) {
console.log("Hello", name);
callback(name);
}
function bye(userName) {
console.log("Good Bye", userName);
}
greet("Anil", bye);
Here:
byeis passed as a callback- It receives the
nameparameter
Inline Callback (Most Common Way)
In real-world JavaScript, callbacks are usually written inline:
greet("Anil", function(userName) {
console.log("Good Bye", userName);
});
This is also called an anonymous callback function.
Callback with setTimeout (Very Important)
setTimeout(() => {
console.log("Hello");
}, 2000);
Explanation:
setTimeouttakes a callback function- It runs after 2 seconds
- This is a built-in callback example
Callback with Arrays (forEach)
let data = ["Anil", "Sidhu", "Sam"];
data.forEach((item) => {
console.log(item);
});
Output:
Anil
Sidhu
Sam
Explanation:
forEachtakes a callback function- It runs for each element in the array
Real-Life Use: API Call Simulation
function makeAPICall(callback) {
setTimeout(() => {
const user = {
name: "Anil Sidhu",
channel: "Code Step By Step"
};
callback(user);
}, 1000);
}
function handleData(data) {
console.log(data);
}
makeAPICall(handleData);
Output (after 1 second):
{ name: "Anil Sidhu", channel: "Code Step By Step" }
Explanation:
- API calls take time (asynchronous)
- Callback runs after data is received
- This pattern is very common in real projects
Where Callback Functions Are Used
Callback functions are commonly used in:
- setTimeout / setInterval
- Array methods (forEach, map, filter, reduce)
- API calls
- File handling (Node.js)
- Event handling (click, submit, etc.)