**Callbacks** are the original async pattern in JavaScript. You pass a function to another function to be called when ready. The **Node.js error-first callback convention**: `callback(error, result)` — first argument is error (null if success). Callbacks led to 'callback hell' — deeply nested callbacks. Promises and async/await solved this.
1Understanding Callback Functions
Callbacks are the original async pattern in JavaScript. You pass a function to another function to be called when ready. The Node.js error-first callback convention: callback(error, result) — first argument is error (null if success). Callbacks led to 'callback hell' — deeply nested callbacks. Promises and async/await solved this.
Always handle errors in Node-style callbacks: if (err) { return handleError(err); }
// Node.js error-first callback pattern
const fs = require('fs');
fs.readFile('./data.json', 'utf8', (err, data) => {
if (err) {
console.error('Failed to read:', err.message);
return;
}
const parsed = JSON.parse(data);
console.log(parsed);
});2Practical Example
Here is a real-world application of Callback Functions showing how it is used in production JavaScript code.
// Callback hell vs Promise chain vs async/await
// Callback hell:
getUser(id, (err, user) => {
getPosts(user.id, (err, posts) => {
getComments(posts[0].id, (err, comments) => {
// deeply nested...
});
});
});
// async/await (clean)
async function load(id) {
const user = await getUser(id);
const posts = await getPosts(user.id);
return getComments(posts[0].id);
}3Best Practices
Follow these guidelines when working with Callback Functions:
1. Follow Node.js convention: callback(error, result)
2. Use Promises or async/await for new code
3. Name callbacks meaningfully: onSuccess, onError, handleData
Tip: Always handle errors in Node-style callbacks: if (err) { return handleError(err); }
// Node.js error-first callback pattern
const fs = require('fs');
fs.readFile('./data.json', 'utf8', (err, data) => {
if (err) {
console.error('Failed to read:', err.message);
return;
}
const parsed = JSON.parse(data);
console.log(parsed);
});