Callback Functions in JavaScript
Understand callback functions in JavaScript: passing functions as arguments, array callbacks, setTimeout and success or error callbacks. Explanation and output.
1// Callback: Function passed as argument to another function23// Example 1: Simple callback4function greet(name, callback) {5 console.log("Hello, " + name);6 callback();7}89greet("John", function() {10 console.log("Callback executed!");11});1213// Example 2: Callback with parameters14function processArray(arr, callback) {15 let result = [];16 for (let item of arr) {17 result.push(callback(item));18 }19 return result;20}2122let numbers = [1, 2, 3, 4, 5];23let doubled = processArray(numbers, function(num) {24 return num * 2;25});2627console.log("\nDoubled:", doubled);2829// Example 3: Using arrow functions30let squared = processArray(numbers, num => num ** 2);31console.log("Squared:", squared);3233// Example 4: setTimeout callback34console.log("\nStart");35setTimeout(function() {36 console.log("This runs after 1 second");37}, 1000);38console.log("End");3940// Example 5: Array methods with callbacks41let arr = [1, 2, 3, 4, 5];4243// forEach44arr.forEach(function(num) {45 console.log("Number:", num);46});4748// map49let doubled2 = arr.map(num => num * 2);50console.log("\nMapped:", doubled2);5152// filter53let evens = arr.filter(num => num % 2 === 0);54console.log("Filtered:", evens);5556// Example 6: Custom callback with error handling57function fetchData(successCallback, errorCallback) {58 let success = true; // Simulate API call5960 if (success) {61 successCallback({ data: "Success!" });62 } else {63 errorCallback("Error occurred");64 }65}6667fetchData(68 function(data) {69 console.log("\nSuccess:", data);70 },71 function(error) {72 console.log("Error:", error);73 }74);
Sample Output
End
Printed right after Start because setTimeout does not pause the program.
This runs after 1 second
The timer callback waits until every other line has run, so it is last.
In this one
- What a callback is and why it is useful
- How to write a function that takes a callback
- Why setTimeout callbacks run after other code
- The success and error callback pattern
How it works
- 1
greet prints Hello, John and runs the callback.
- 2
processArray doubles, then squares, the numbers.
- 3
setTimeout schedules a message and the code continues to End.
- 4
forEach, map and filter run their callbacks.
- 5
fetchData calls the success callback.
- 6
Finally the timer fires and prints its message.
Edge cases
Calling instead of passing
greet("John", sayHi()) passes the result, not the function.
Pass the name without brackets: greet("John", sayHi).
Missing return in a callback
processArray(arr, n => { n * 2 }) gives undefined values.
Braces need return. Write n => n * 2 or add return.
setTimeout(fn, 0)
It still runs after the current code.
The delay is a minimum. The callback waits for the call stack to be empty.
What's going on
A callback is a function you pass into another function so it can call it later. You already use them with forEach and map. Callbacks let one function decide what happens next without knowing the details.
Example 1 is the simplest. greet prints a hello, then calls the callback you gave it.
Example 2 writes processArray, a small version of map. It runs your callback on every item and collects what it returns. Passing a doubling function gives [2, 4, 6, 8, 10]. Example 3 passes an arrow function that squares instead. The same processArray does two different jobs. If your callback forgets to return, every result is undefined.
Example 4 uses setTimeout, the example everyone copies. setTimeout(fn, 1000) asks JavaScript to run fn after at least one second. It does not pause the program. JavaScript keeps going and prints "End" right away. The timer callback runs only after all the normal code has finished. Even setTimeout(fn, 0) waits until the current code is done, so it is never immediate.
Look at the output. "This runs after 1 second" is the very last line, after the forEach numbers and even after "Success". That is because every other line is synchronous and runs first.
Example 5 shows forEach, map and filter, which all take callbacks. Example 6 passes two callbacks, one for success and one for error. Older Node APIs work this way. Promises and async/await later replaced most of this style.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is a callback?
Pick an answer to check it.
Question 2
In this program, which line prints last?
Pick an answer to check it.
Questions people ask
Is a callback always asynchronous?
No. forEach callbacks run right away. setTimeout callbacks run later.
What is callback hell?
Many nested callbacks inside each other. Promises and async/await make that code flatter.
Why does the timer message print last?
All normal code runs first. The timer only fires when JavaScript is free.