Home Courses Callback Function Explained - Private Scope in JS

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:

  1. Passed inside another function
  2. 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:

  1. greet function takes a function as a parameter
  2. That function becomes the callback
  3. 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:

  1. bye is passed as a callback
  2. It receives the name parameter


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:

  1. setTimeout takes a callback function
  2. It runs after 2 seconds
  3. 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:

  1. forEach takes a callback function
  2. 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:

  1. API calls take time (asynchronous)
  2. Callback runs after data is received
  3. This pattern is very common in real projects


Where Callback Functions Are Used

Callback functions are commonly used in:

  1. setTimeout / setInterval
  2. Array methods (forEach, map, filter, reduce)
  3. API calls
  4. File handling (Node.js)
  5. Event handling (click, submit, etc.)


Share this lesson: