Introduction
Callbacks let you run code after something else finishes, like waiting for a friend before starting a game. But too many callbacks inside each other can make code hard to read and fix.
Jump into concepts and practice - no test required
Callbacks let you run code after something else finishes, like waiting for a friend before starting a game. But too many callbacks inside each other can make code hard to read and fix.
function doSomething(data, callback) {
// do work
callback(result);
}
doSomething(input, function(result) {
// handle result
});function greet(name, callback) {
callback(`Hello, ${name}!`);
}
greet('Alice', function(message) {
console.log(message);
});readFile('file.txt', function(err, data) { if (err) { console.error('Error:', err); } else { console.log('File data:', data); } });
doStep1(function(result1) {
doStep2(result1, function(result2) {
doStep3(result2, function(result3) {
console.log('Final:', result3);
});
});
});This program runs three steps one after another using callbacks. Each step waits half a second, then calls the next. The nested callbacks show how callback hell looks.
function step1(callback) {
setTimeout(() => {
console.log('Step 1 done');
callback('data from step 1');
}, 500);
}
function step2(data, callback) {
setTimeout(() => {
console.log('Step 2 done with', data);
callback('data from step 2');
}, 500);
}
function step3(data, callback) {
setTimeout(() => {
console.log('Step 3 done with', data);
callback('all steps done');
}, 500);
}
step1(function(result1) {
step2(result1, function(result2) {
step3(result2, function(finalResult) {
console.log(finalResult);
});
});
});Too many nested callbacks make code hard to read and maintain.
Use named functions or promises to avoid callback hell.
Always handle errors in callbacks to avoid silent failures.
Callbacks run code after an action finishes.
Nested callbacks cause callback hell, making code messy.
Better patterns exist to keep code clean and easy to follow.
function first(callback) {
setTimeout(() => {
console.log('First');
callback();
}, 100);
}
function second() {
console.log('Second');
}
first(second);readFile('file1.txt', function(err, data1) {
if (err) throw err;
readFile('file2.txt', function(err, data2) {
if (err) throw err;
readFile('file3.txt', function(err, data3) {
if (err) throw err;
console.log(data1, data2, data3);
});
});
});