Callbacks
Overview
In JavaScript, functions are 'First-Class Citizens'. This means they can be treated like any other variable: they can be assigned to variables, returned from functions, and—most importantly—passed as arguments into other functions.
A function passed as an argument to another function is called a 'Callback'. Callbacks are the foundation of asynchronous JavaScript (like waiting for data or listening for clicks).
Syntax
// The parent function accepts a parameter called 'callback'
function greet(name, callback) {
console.log("Hi " + name);
// Executes the passed function!
callback();
}
// A standard function
function askQuestion() {
console.log("How are you?");
}
// Pass 'askQuestion' as a callback (Notice: NO parenthesis!)
greet("Kartik", askQuestion);Common Pitfalls
- Passing
askQuestion()with parenthesis instead ofaskQuestion. If you use parenthesis, the function runs immediately during evaluation, and you end up passing its return value (oftenundefined) instead of passing the function itself!
Interview Questions
A callback is a function passed as an argument to another function, which is then invoked inside the outer function to complete some kind of routine or action.
When multiple asynchronous operations depend on each other, you have to nest callbacks inside of callbacks, creating a deeply nested 'Pyramid of Doom' that is incredibly hard to read and debug. Promises and async/await were invented to solve this.
Real-World Example
React and the DOM rely entirely on callbacks for event handling. You pass a function to be executed later, only when the user interacts.
<button onClick={handleSubmit}>Submit</button>Check Your Knowledge
Test your understanding of Callbacks with these quick questions.