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 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);
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.