Thursday, August 21, 2025

Javascript Module 54

  Module 54 : Callbacks Revisited 

Section 1: What is a Callback?

A callback is a function passed as an argument to another function, which is then invoked inside that outer function to complete some kind of routine or action.

                










πŸ”Ή Syntax:

function greet(name) { console.log("Hello, " + name); } function processUserInput(callback) { const name = "Rehana"; callback(name); } processUserInput(greet);

Explanation:

greet is a function.

processUserInput takes a function (callback) as a parameter.

It calls the callback with a predefined name.


Section 2: Synchronous vs Asynchronous Callbacks

πŸ”Έ Synchronous Callback:

Executed immediately during the execution of the higher-order function.

function calculate(a, b, callback) { let result = a + b; callback(result); } calculate(5, 3, function(res) { console.log("Result:", res); // Result: 8 });

πŸ”Έ Asynchronous Callback:

Executed later, often in response to an event or after a timer.

function getData(callback) { setTimeout(() => { callback("Fetched data"); }, 1000); } getData((data) => { console.log(data); // Fetched data });


Section 3: Error-First Callback Convention (Node.js Style)

Popular in Node.js, this pattern helps to handle success and failure with the same callback.

                










function readFile(callback) { const error = false; const data = "File content here"; if (error) { callback("Error reading file", null); } else { callback(null, data); } } readFile(function(err, data) { if (err) { console.error(err); } else { console.log(data); } });


Section 4: Callback Hell (Pyramid of Doom)

Problem:

Nested callbacks become hard to read and maintain.

doStep1(function(result1) { doStep2(result1, function(result2) { doStep3(result2, function(result3) { console.log(result3); }); }); });

Specialist Insight:

Many modern JS developers avoid callback hell using Promises or Async/Await for better code flow and readability.


Section 5: Case – Form Submission Simulation

function submitForm(data, callback) { console.log("Submitting form..."); setTimeout(() => { if (data.username && data.password) { callback(null, "Form submitted successfully"); } else { callback("Missing credentials"); } }, 2000); } submitForm({ username: "jsdev", password: "12345" }, function(err, successMsg) { if (err) { console.error("Error:", err); } else { console.log(successMsg); } });


 Section 6: 

1: Build a Simple Timer with Callback

        


                


function startTimer(seconds, callback) { console.log(`Timer started for ${seconds} seconds`); setTimeout(() => { callback(); }, seconds * 1000); } startTimer(3, () => { console.log("Time's up!"); });

✅ Expected Output:

Timer started for 3 seconds

(Time delay of 3 seconds)

Time's up!


2: Create Your Own Event Handler

function onClick(callback) { console.log("User clicked (simulated)"); callback(); } function showMessage() { console.log("Button clicked!"); } onClick(showMessage);

 Explanation:

This mimics how DOM event listeners work internally in JavaScript.


 Section 7:

Exercises 

Exercise 1:

Write a function that performs multiplication of two numbers and passes the result to a callback.

function multiply(a, b, callback) { // Your code here }

✅ Solution:

function multiply(a, b, callback) { let result = a * b; callback(result); } multiply(4, 5, function(result) { console.log("Multiplication result:", result); });


Exercise 2:

Simulate a login system using callbacks.

✅ Template:

function login(username, password, callback) { // Simulate server check } login("user", "pass", function(err, msg) { // Handle result });

✅ Solution:

function login(username, password, callback) { setTimeout(() => { if (username === "admin" && password === "1234") { callback(null, "Login successful"); } else { callback("Invalid credentials"); } }, 1000); } login("admin", "1234", function(err, msg) { if (err) { console.error(err); } else { console.log(msg); } });


Section 8: Applications

AJAX Requests: Used heavily before Promises/fetch

Node.js File System: Uses callbacks in fs.readFile()

User Authentication

Animation and Game Events

Event Listeners in Web Development


 Section 9: Callback to Promises Migration – Research Insight

                  










  Scenario Migration:

// Callback style function fetchData(callback) { setTimeout(() => { callback(null, "Data loaded"); }, 1000); } // Converted to Promise function fetchDataPromise() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("Data loaded"); }, 1000); }); } fetchDataPromise().then(data => { console.log(data); });

 Research Tip from Coding Experts:

“Use callbacks when working with libraries that are not Promise-aware (e.g., some legacy Node.js modules). But for scalability and maintenance, prefer Promises or Async/Await in modern codebases.” — Kyle Simpson (You Don’t Know JS)


  Summary

Concept

Description

Callback

A function passed as a parameter to another

Sync vs Async

Sync: immediate, Async: scheduled later

Callback Hell

Deep nesting – hard to read & maintain

Error-first Callbacks

function(err, data) for handling both outcomes

Replaced by

Promises or Async/Await for better readability



  Conclusion

Callbacks are fundamental to understanding.

                









 how JavaScript handles asynchronous behavior. While they are sometimes replaced with Promises or libraryAsync/Await, mastering them is essential for legacy systems,  handling, and certain  interactions.


No comments:

Post a Comment

πŸ‘‰ “How to Build a Professional Admin Dashboard Using Bootstrap, PHP, MySQL & Python (Complete Step-by-Step Guide)”

Building and Styling a Dashboard using Bootstrap, PHP, SQL, and Python. Modern web applications rely heavily on interactive dashboards to vi...