Js Callbacks in JavaScript
? JavaScript Callbacks
What is a Callback?
A callback is a function passed as an argument to another function.
It is called (invoked) after some operation finishes, especially asynchronous ones.
Enables code to run after an event or async task completes.
Basic Example of Callback
function greet(name, callback) { console.log(`Hello, ${name}!`); callback();}function sayGoodbye() { console.log("Goodbye!");}greet("Alice", sayGoodbye);// Output:// Hello, Alice!// Goodbye!Callbacks with Asynchronous Code
function fetchData(callback) { setTimeout(() => { callback("Data loaded"); }, 1000);}fetchData((message) => { console.log(message);});The callback runs after 1 second, simulating an async operation.
Why Use Callbacks?
Handle async operations like:
Fetching data
Timers
Event handling
Maintain order of execution for async tasks.
Callback Hell (Pyramid of Doom)
Nesting many callbacks leads to hard-to-read code:
doSomething(function(result) { doSomethingElse(result, function(newResult) { doThirdThing(newResult, function(finalResult) { console.log("Done!"); }); });});Alternatives to Callbacks
Promises and Async/Await are modern, cleaner ways to handle async flows.
Want me to show you how to convert callback code into Promises or explain callback error handling?