JavaScript Notes
Understand JavaScript callback functions deeply – synchronous vs async callbacks, callback hell, event handlers, array methods with real-world examples and interview Q&A.
Introduction
A callback function is one of the most fundamental concepts in JavaScript. Almost everything in JavaScript — event handlers, array methods, setTimeout, API calls, Node.js I/O — uses callbacks.
Understanding callbacks means understanding how JavaScript handles "do this, then do that" logic, which is the heart of both synchronous and asynchronous programming.
Basic Syntax
function doSomething(callback) {
// do some work...
callback(); // call the function that was passed in
}
function sayHello() {
console.log("Hello!");
}
doSomething(sayHello); // passing sayHello as a callbackHello!
Notice: sayHello is passed without parentheses — you pass the function itself, not its result.
Synchronous Callbacks
A synchronous callback is executed immediately as part of the calling function's execution.
function greetUser(name, formatter) {
const formatted = formatter(name);
console.log(formatted);
}
function toUpperCase(str) {
return str.toUpperCase();
}
greetUser("riya", toUpperCase);RIYA
Step-by-Step Execution Trace:
Callbacks in Built-in Array Methods
The most common place you'll see callbacks is in array methods.
.forEach() – Loop over every element
apple banana mango
.map() – Transform each element
[90, 180, 270]
.filter() – Keep items that pass a test
[72, 88, 91]
.sort() – Custom sort with callback
[1, 5, 30, 200]
Asynchronous Callbacks
An asynchronous callback is called later, after a delay or an event, not immediately.
setTimeout Example:
console.log("Start");
setTimeout(function () {
console.log("Inside callback – after 2 seconds");
}, 2000);
console.log("End");Start End Inside callback – after 2 seconds
Notice: "End" prints before the callback. JavaScript doesn't wait — it continues running and the callback fires when the timer is up.
Event Listener Callback:
// In browser environment
document.getElementById("btn").addEventListener("click", function () {
console.log("Button was clicked!");
});Button was clicked! ← (only when user clicks)
Custom Callback Function Pattern
You can build your own functions that accept callbacks — just like built-in methods do.
Result: 16 Result: 27
Memory Diagram – How Callbacks Work
Real World Analogy
Callbacks are like a restaurant pager system. 1. You order food at the counter (you call a function) 2. You give them your buzzer (you pass a callback) 3. You sit down and do other things (JS continues executing) 4. When food is ready, the buzzer goes off (callback is triggered) 5. You go pick up your food (callback runs) The restaurant (the function) decides when to call you back. You just provide the "what to do when ready" logic.
Callback Hell (and how to avoid it)
When callbacks are nested inside callbacks, code becomes hard to read — this is called "Callback Hell" or the "Pyramid of Doom".
Solutions:
- Named functions instead of anonymous callbacks
- Promises – flat
.then()chains - async/await – cleaner async code
Error-First Callback Pattern (Node.js Style)
In Node.js, callbacks follow an error-first convention: the first parameter is always the error.
function readFile(path, callback) {
// simulate file read
const error = null;
const data = "File contents here";
callback(error, data);
}
readFile("./notes.txt", function (err, data) {
if (err) {
console.log("Error:", err);
return;
}
console.log("Data:", data);
});Data: File contents here
Common Mistakes
❌ Mistake 1: Calling the callback immediately instead of passing it
// WRONG – () calls the function RIGHT NOW, passes its return value
doSomething(sayHello()); // passes undefined, not the function
// CORRECT – pass the reference without ()
doSomething(sayHello);❌ Mistake 2: Not handling errors in async callbacks
// WRONG
fetchData(url, function (data) {
console.log(data.name); // crashes if data is null
});
// CORRECT
fetchData(url, function (err, data) {
if (err) return console.error(err);
console.log(data.name);
});❌ Mistake 3: Forgetting callbacks are asynchronous
let result;
setTimeout(function () {
result = 42;
}, 1000);
console.log(result); // undefined – callback hasn't run yet!undefined
// CORRECT – use result INSIDE the callback
setTimeout(function () {
const result = 42;
console.log(result); // 42 – correct!
}, 1000);❌ Mistake 4: Calling callback multiple times accidentally
// WRONG
function doWork(callback) {
callback("done");
callback("done again"); // called twice!
}
// CORRECT – call callback only once
function doWork(callback) {
callback("done");
}Interview Questions
Q1. What is a callback function in JavaScript?
A callback function is a function passed as an argument to another function, which is then invoked inside that outer function at the appropriate time — either synchronously or asynchronously.
Q2. What is the difference between synchronous and asynchronous callbacks?
- Synchronous callback: Executed immediately during the calling function's execution (e.g.,
Array.map,Array.forEach) - Asynchronous callback: Executed later after an event or delay (e.g.,
setTimeout, event listeners, API calls)
Q3. What is callback hell and how do you avoid it?
Callback hell is deeply nested callbacks that make code hard to read. Solutions: use named functions, Promises, or async/await.
Q4. What is the error-first callback pattern?
A Node.js convention where the first argument of a callback is an error object (null if no error) and the second is the result.
Q5. Why are callbacks fundamental to JavaScript?
JavaScript is single-threaded with an event loop. Callbacks allow non-blocking execution — the program can continue running while waiting for I/O, timers, or user events.
Q6. Can arrow functions be used as callbacks?
Yes, and they are very common:
[2, 4, 6]
Q7. What happens if you don't call the callback?
The caller never receives the result. In async operations, execution that depends on the callback simply never happens — a common source of bugs.
Q8. What is the difference between a callback and a higher-order function?
The higher-order function is the function that *receives* another function. The callback is the function that *is passed in and called later*.
Key Takeaways
- ✅ A callback is a function passed as an argument to be called later
- ✅ Synchronous callbacks run immediately; async callbacks run after an event/delay
- ✅ Array methods (map, filter, forEach) use synchronous callbacks
- ✅ setTimeout, addEventListener use asynchronous callbacks
- ✅ Always pass function reference (no
()) unless intentional - ✅ Error-first pattern (
err, data) is standard in Node.js - ✅ Deep nesting → callback hell → solve with Promises or async/await
- ✅ Callbacks are the foundation of JavaScript's event-driven model
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Callback Functions Explained – Synchronous & Asynchronous.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, functions, callback, function
Related JavaScript Master Course Topics