A callback is a function passed into another function to be executed later. This may sound complex, but it’s quite simple. You’ve likely seen callbacks in action before, such as in event listeners.
Example of a Callback
Consider an event listener:
This can be rewritten using a callback function:
Why Use Callbacks?
Callbacks are useful for two main reasons:
- Easily Swap Code: Callbacks allow you to change the functionality without altering the overall structure.
- Prevent Blocking in Asynchronous Code: Callbacks help manage asynchronous tasks without blocking the main execution thread.
Asynchronous Code
Synchronous code runs sequentially, while asynchronous code does not. For example, an event listener is asynchronous because its callback executes only when the event occurs.
The Event Loop
JavaScript uses an event loop to manage asynchronous operations. It maintains a call stack (todo-list) and an event queue (waiting-list). When an asynchronous event occurs, the callback is added to the event queue and executed when the call stack is clear.
more infos, see on Philip Roberts at JSConf Talk
Creating Callbacks
To create a callback, define a function that accepts a callback as an argument and then execute the callback within it:
The callback also can accept arguments:
Summary
- A callback is a function passed to another function to be executed later.
- Callbacks are useful for flexible code and managing asynchronous tasks.
- JavaScript’s event loop handles asynchronous operations.
- Creating a callback involves defining a function that accepts and executes another function.
No exercises are required for this lesson. The main takeaway is understanding what a callback is and how to use it.