Module 22 : Callback Functions in javascript
๐ง What is a Callback Function?
Definition: A callback function is a function passed as an argument to another function and is executed after some operation has been completed.
๐ Analogy
Imagine you're ordering a pizza ๐:
You call the pizza place and order.
Instead of waiting, you give your phone number (callback).
When the pizza is ready, they call you back.
The "call you back" part is the callback function. You continue doing your work and the function is invoked later — just like JavaScript’s asynchronous behavior.
๐ก Basic Syntax and Example
javascript
code
function greetUser(name) { alert('Hello ' + name); } function processUser(callback) { const name = prompt('Please enter your name.'); callback(name); // invoking callback function } processUser(greetUser);
๐ Explanation:
greetUser is passed to processUser.
processUser takes a callback and calls it with a parameter.
This is useful for reusability and dynamic behavior.
1: Write Your Own Callback
๐ฏ Goal: Understand basic callback function behavior
javascript
code
function calculate(num1, num2, callback) { const result = num1 + num2; callback(result); } function showResult(res) { console.log("The result is:", res); } calculate(5, 10, showResult);
✅ Try It:
Change + to *, and observe the output. Try writing a subtraction or division callback too.
๐ Synchronous vs Asynchronous Callbacks
๐น Synchronous Callback Example
javascript
code
function syncCallback(name, callback) { console.log("Start"); callback(name); console.log("End"); } syncCallback("Reha", function(name) { console.log("Hello " + name); });
Output:
sql
code
Start
Hello Reha
End
๐น Asynchronous Callback Example (setTimeout)
javascript
code
function asyncCallback(name, callback) { console.log("Start"); setTimeout(() => { callback(name); }, 2000); console.log("End"); } asyncCallback("Reha", function(name) { console.log("Hello " + name); });
Output:
pgsql
code
Start
End
Hello (after 2 sec)
๐ง Concept:
Sync: Runs immediately
Async: Waits for something (like a timer or network request)
๐ง Use Case 1: Event Handling
javascript
code
document.getElementById("myBtn").addEventListener("click", function() { alert("Button Clicked!"); });
Here, the function inside addEventListener is a callback that is executed when the user clicks.
๐ง Use Case 2: Array Methods
javascript
code
const numbers = [1, 2, 3]; const doubled = numbers.map(function(num) { return num * 2; }); console.log(doubled); // [2, 4, 6]
๐ Explanation:
The map() method takes a callback function that tells it how to transform each item.
๐ Advanced Example: Simulating an API Call
javascript
code
function fetchData(callback) { setTimeout(() => { const data = { name: "Syeda Rehana", age: 24 }; callback(data); }, 1000); } function processData(userData) { console.log("User fetched:", userData.name, userData.age); } fetchData(processData);
๐ use:
Useful in web development when you fetch user data from APIs.
2: Build Your Own Asynchronous Callback
Task: Create a fake API to fetch product data using callbacks.
javascript
code
function getProduct(callback) { setTimeout(() => { const product = { id: 1, name: "Laptop", price: 49999 }; callback(product); }, 1500); } function displayProduct(product) { console.log("Product:", product.name, "Price:", product.price); } getProduct(displayProduct);
✅ Modify the callback to apply a discount or show in alert box
๐ Research Insight: Why Callbacks Matter
JavaScript uses non-blocking asynchronous programming to handle things like:
HTTP requests
Event listeners
Timers
File reading (in Node.js)
๐งต Callback Problem
Nested callbacks can become hard to manage:
javascript
code
loginUser("Rehana", () => { getProfile(() => { loadDashboard(() => { // very hard to read }); }); });
๐ ️ Solution: Use Promises or Async/Await (covered in next module).
✅ Best Practices
Do
Avoid
Name your callback functions
Anonymous nested functions everywhere
Handle errors in callbacks
Assuming success always
Use arrow functions for cleaner syntax
Callback inside callback inside callback
Move toward Promises for complex flows
Sticking to callbacks only for async tasks
๐ง Questions
What is a callback function?
What's the difference between synchronous and asynchronous callbacks?
What issue does "callback" describe?
Modify a callback to add logging before and after it runs.
๐ฃ️ Presentation Tips
Start with analogy (e.g., pizza order, phone calls)
Live-code a simple callback
Show browser dev tools, console.log to trace flow
Show async delay with setTimeout
Compare it with Promises to build curiosity
Give incremental exercises
Event-Based Callback System
Task: Create a mini event handler system using callbacks.
javascript
code
function onEvent(message, callback) { console.log("System Message:", message); callback(); } onEvent("New message received", function() { console.log("Opening message view..."); });
๐ Enhance this by adding a time delay, or multiple events.
๐ Summary
A callback is a function passed to another function to be executed later.
JavaScript uses callbacks heavily in async operations and event-driven systems.
Callbacks promote code reuse and modular design.
Be cautious of callback l; use promises or async/await when needed.