Callback Functions in JavaScript

Pass a function into a function. setTimeout is the example everyone copies.

IntermediateFunction ProgramsExample 2 of 3
callback-functions.js
1// Callback: Function passed as argument to another function
2
3// Example 1: Simple callback
4function greet(name, callback) {
5 console.log("Hello, " + name);
6 callback();
7}
8
9greet("John", function() {
10 console.log("Callback executed!");
11});
12
13// Example 2: Callback with parameters
14function processArray(arr, callback) {
15 let result = [];
16 for (let item of arr) {
17 result.push(callback(item));
18 }
19 return result;
20}
21
22let numbers = [1, 2, 3, 4, 5];
23let doubled = processArray(numbers, function(num) {
24 return num * 2;
25});
26
27console.log("\nDoubled:", doubled);
28
29// Example 3: Using arrow functions
30let squared = processArray(numbers, num => num ** 2);
31console.log("Squared:", squared);
32
33// Example 4: setTimeout callback
34console.log("\nStart");
35setTimeout(function() {
36 console.log("This runs after 1 second");
37}, 1000);
38console.log("End");
39
40// Example 5: Array methods with callbacks
41let arr = [1, 2, 3, 4, 5];
42
43// forEach
44arr.forEach(function(num) {
45 console.log("Number:", num);
46});
47
48// map
49let doubled2 = arr.map(num => num * 2);
50console.log("\nMapped:", doubled2);
51
52// filter
53let evens = arr.filter(num => num % 2 === 0);
54console.log("Filtered:", evens);
55
56// Example 6: Custom callback with error handling
57function fetchData(successCallback, errorCallback) {
58 let success = true; // Simulate API call
59
60 if (success) {
61 successCallback({ data: "Success!" });
62 } else {
63 errorCallback("Error occurred");
64 }
65}
66
67fetchData(
68 function(data) {
69 console.log("\nSuccess:", data);
70 },
71 function(error) {
72 console.log("Error:", error);
73 }
74);

Output

Hello, John
Callback executed!

Doubled: [ 2, 4, 6, 8, 10 ]

Squared: [ 1, 4, 9, 16, 25 ]

Start
End
This runs after 1 second
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Mapped: [ 2, 4, 6, 8, 10 ]

Filtered: [ 2, 4 ]

Success: { data: 'Success!' }

What's going on

setTimeout(() => ..., 0) runs after the current stack. Not immediately.

Forget return in a callback and the next then() gets undefined.