The Error Parameter Convention
You'll learn why error-first callbacks always put the error parameter first, and what it means when that parameter is null or undefined.
The First Parameter Rule
In error-first callbacks, the first parameter is always reserved for errors. This isn't enforced by JavaScript—it's a convention that Node.js popularized and the community adopted for consistency.
When you call a callback:
- If something went wrong, pass an
Errorobject as the first argument - If everything succeeded, pass
nullorundefinedas the first argument
This uniform pattern means every callback consumer knows exactly where to look for errors, no guessing required.
Why This Order Matters
Think of it like a traffic light at an intersection: red always means stop, green always means go. By putting the error first, you're forced to check it before accessing the success data. It's a safety-first design.
function readFile(path, callback) {
// If failure:
callback(new Error('File not found'), undefined);
// If success:
callback(null, fileContents);
}
The consumer checks the error before touching the data:
readFile('data.txt', (err, data) => {
if (err) {
// Handle error
return;
}
// Safe to use data
});
The Success Signal
When err is null or undefined, it's the universal signal: "No error occurred, proceed safely." You'll often see code check if (err) because both null and undefined are falsy.
Key Takeaway: The error-first callback convention reserves the first parameter for errors, using null/undefined to signal success—creating a predictable, safe pattern for handling asynchronous operations.