What is a Callback?
A callback is a function that is passed as an argument to another function and is executed after some operation has been completed. It's called a "callback" because it gets "called back" at a later time.
JavaScript is asynchronous and non-blocking, meaning it doesn't wait for long operations to complete before moving to the next line of code.
- Handling API responses
- Reading/writing files
- Database operations
- Event handling
- Timer functions
Types of Callbacks
Synchronous callbacks are executed immediately within the function they're passed to.
Asynchronous callbacks are executed later, after an asynchronous operation completes.
Real-World Examples
Event listeners use callbacks to handle user interactions.
Node.js follows a convention where the first parameter of a callback is always an error object.
Multiple callbacks can be chained to perform sequential operations.
Common Problems & Solutions
When you have multiple nested callbacks, code becomes hard to read and maintain.
- Use Promises: Modern way to handle async operations
- Use Async/Await: Even cleaner syntax built on promises
- Named Functions: Instead of anonymous functions
- Modularize Code: Break into smaller functions
- Always handle errors in callbacks
- Keep callbacks short and focused
- Use named functions for better readability
- Follow error-first convention in Node.js
- Consider using Promises or Async/Await for complex async flows
- Don't nest callbacks too deeply
- Don't forget to handle errors
- Don't use callbacks when Promises are more appropriate
- Don't create memory leaks by not cleaning up event listeners
Key Takeaways
- ✅ Callbacks are functions passed as arguments to other functions
- ✅ Executed later after some operation completes
- ✅ Can be synchronous (array methods) or asynchronous (setTimeout, API calls)
- ✅ Error-first convention is standard in Node.js
- ✅ Avoid callback hell by using Promises or Async/Await
- ✅ Always handle errors properly in callbacks