Introduction
Have you ever wondered how JavaScript knows what to do after completing a task like waiting for a timer, handling user clicks, or fetching data from a server? That’s where callback functions come in. They are foundational to writing effective, non-blocking, and clean JavaScript code.
In this post, we’ll dive into the essentials of callbacks, covering what they are, the different ways to write them, and the crucial distinction between synchronous and asynchronous callbacks.
What is a Callback Function?
In JavaScript, functions are first-class citizens, meaning they can be passed around like variables.
A callback is simply a function passed as an argument to another function, which then gets executed later, either immediately or after a specific event or operation.
Here’s a simple example:
function greet(name) {
console.log("Hello, " + name);
}
function runCallback(callback) {
const name = "Rowland";
callback(name); // invoke the callback function
}
runCallback(greet); // Output: Hello, Rowland
In this code, the greet
function is the callback, passed as an argument to runCallback
and executed inside it.
Important Note:
When passing the function as a callback, you pass its reference by not including parentheses like this;
runCallback(greet)
.Adding parentheses as in
runCallback(greet())
would executegreet
immediately and pass its returned value (which would beundefined
in this case) as the argument, which is incorrect for a callback.
Ways of Writing Callback Functions
Callbacks can be defined in a few different ways:
Named Callbacks
A named callback is a regular function definition that has an explicit name, like the greet
function in the example above.
Benefits:
- Reusability: You can use the same function as a callback in multiple places.
- Readability: Clearer code structure when the logic is complex.
- Debugging: The function’s name appears in the call stack, making debugging easier.
Anonymous Callbacks
An anonymous callback is a function without a name that is passed directly as an argument, usually defined inline.
function runCallback(callback) {
const name = "Rowland";
callback(name); // invoke the callback function
}
runCallback(function(name) {
console.log("Hello, " + name);
}); // Output: Hello, Rowland
Arrow Function Callbacks
This is similar to anonymous callbacks but uses the modern ES6 arrow function syntax for a more concise and readable style.
function runCallback(callback) {
const name = "Rowland";
callback(name); // Invoke the callback function
}
runCallback((name) => {
console.log(`Hello, ${name}`);
}); // Output: Hello, Rowland
Types of Callback Functions
Callbacks primarily fall into two categories, based on when they are executed:
Synchronous Callbacks
A synchronous callback is executed immediately within the function it’s passed to, completing before the next line of code runs.
Common Use Cases:
- Array Methods:
forEach
,map
,filter
, etc. - Custom utility functions
- Higher-Order Functions (HOF).
Example with map
array method:
const arr = [1, 2, 3];
function doubleNumber(num) {
return num * 2
}
const doubled = arr.map(doubleNumber); // The callback runs immediately for each item.
console.log(doubled); // [2, 4, 6]
In this case, doubleNumber
is a named callback passed to the arr.map()
method.
Asynchronous Callbacks
An asynchronous callback is executed after an asynchronous operation completes, not immediately. This allows the JavaScript engine to move on to the next line of code while the operation (like a timer or network request) is pending.
Common Asynchronous Operations:
setTimeout
- Event Listeners (e.g.,
document.addEventListener(‘event’, callback)
) - HTTP Requests (e.g., using
fetch
)
Example with setTimeout
:
setTimeout(function() {
console.log("Runs after 2 seconds");
}, 2000);
console.log("This will execute first");
Output in the console:
This will execute first
Runs after 2 seconds
The JS engine doesn’t wait for the timer, so the second console.log
executes immediately, and the callback inside setTimeout
runs only after the 2000ms (2s) delay.
Conclusion
Callback functions are a core concept in JavaScript, crucial for understanding how the language manages function execution, especially with asynchronous tasks.
To Recap:
- Callbacks are functions passed into other functions to be invoked later.
- They can be written as named, anonymous, or arrow functions.
- Synchronous callbacks run immediately (e.g., in array methods like map and forEach).
- Asynchronous callbacks run after an operation completes (e.g., setTimeout, event listeners, fetch).
Understanding how and when callbacks execute is essential and sets a strong foundation for learning deeper concepts like Promises and async/await. You’ll find callbacks are everywhere as you continue to write more JavaScript!
Top comments (0)