Introduction to Callbacks in JavaScript

Introduction to Callbacks in JavaScript

Introduction to Callbacks in JavaScript

A callback function is passed as an argument to another function and executed later. This is useful for handling asynchronous operations, event handling, and customizing behavior.

🔹 Why Use Callbacks?

Delays execution until an event happens
Handles asynchronous operations like file reading, API requests, and timers
Prevents blocking the main thread

🔹 Basic Callback Example

A callback is simply a function passed as an argument.

function greet(name, callback) { console.log("Hello, " + name); callback(); } function sayGoodbye() { console.log("Goodbye!"); } greet("Alice", sayGoodbye);
Hello, Alice Goodbye!

sayGoodbye is executed after greet completes.

🔹 Callbacks for Asynchronous Operations

JavaScript is non-blocking, so callbacks help handle asynchronous tasks like fetching data.

Example: Using setTimeout

function fetchData(callback) { console.log("Fetching data..."); setTimeout(() => { callback("Data received"); }, 2000); } fetchData((message) => { console.log(message); });

Output:

Fetching data... (Data appears after 2 seconds) Data received

✔ The callback waits until the data is ready.

🔹 Callbacks for Handling Events

Callbacks are commonly used for event listeners.

document.getElementById("btn").addEventListener("click", function () { console.log("Button clicked!"); });

✔ The function inside addEventListener executes only when the button is clicked.

🔹 Nested Callbacks (Callback Hell)

When multiple callbacks are nested, it becomes hard to read.

function step1(callback) { setTimeout(() => { console.log("Step 1 complete"); callback(); }, 1000); } function step2(callback) { setTimeout(() => { console.log("Step 2 complete"); callback(); }, 1000); } function step3() { setTimeout(() => { console.log("Step 3 complete"); }, 1000); } // Callback Hell step1(() => { step2(() => { step3(); }); });

Output (with 1-second delays)

Step 1 complete Step 2 complete Step 3 complete

✔ But nesting too many callbacks can make code hard to read.

🔹 Avoiding Callback Hell with Promises

Using Promises instead of callbacks makes code cleaner.

function step1() { return new Promise((resolve) => { setTimeout(() => { console.log("Step 1 complete"); resolve(); }, 1000); }); } function step2() { return new Promise((resolve) => { setTimeout(() => { console.log("Step 2 complete"); resolve(); }, 1000); }); } function step3() { return new Promise((resolve) => { setTimeout(() => { console.log("Step 3 complete"); resolve(); }, 1000); }); } // Using Promises instead of callback nesting step1() .then(step2) .then(step3);

Promises help write readable, maintainable async code.

🔹 Summary

✔ A callback is a function passed as an argument to another function
✔ Callbacks handle async tasks, such as timers, file reading, and API calls
Too many nested callbacks lead to "callback hell"
Promises and async/await can make code cleaner

🚀 Want to learn more? Let me know! 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close