Tuesday, July 1, 2025

Javascript Module 22

 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.



No comments:

Post a Comment

Javascript Module 24

  Javascript Module 24 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test A...