Callback Functions
Program demonstrating callback functions
JavaScript Callback Functions Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Callback: Function passed as argument to another function
// Example 1: Simple callback
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
greet("John", function() {
console.log("Callback executed!");
});
// Example 2: Callback with parameters
function processArray(arr, callback) {
let result = [];
for (let item of arr) {
result.push(callback(item));
}
return result;
}
let numbers = [1, 2, 3, 4, 5];
let doubled = processArray(numbers, function(num) {
return num * 2;
});
console.log("\nDoubled:", doubled);
// Example 3: Using arrow functions
let squared = processArray(numbers, num => num ** 2);
console.log("Squared:", squared);
// Example 4: setTimeout callback
console.log("\nStart");
setTimeout(function() {
console.log("This runs after 1 second");
}, 1000);
console.log("End");
// Example 5: Array methods with callbacks
let arr = [1, 2, 3, 4, 5];
// forEach
arr.forEach(function(num) {
console.log("Number:", num);
});
// map
let doubled2 = arr.map(num => num * 2);
console.log("\nMapped:", doubled2);
// filter
let evens = arr.filter(num => num % 2 === 0);
console.log("Filtered:", evens);
// Example 6: Custom callback with error handling
function fetchData(successCallback, errorCallback) {
let success = true; // Simulate API call
if (success) {
successCallback({ data: "Success!" });
} else {
errorCallback("Error occurred");
}
}
fetchData(
function(data) {
console.log("\nSuccess:", data);
},
function(error) {
console.log("Error:", error);
}
);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!' }Understanding Callback Functions
This program demonstrates callback functions in JavaScript.
Callback Function Definition
A callback is a function passed as an argument to another function, to be executed later.
Example 1: Simple Callback
Basic callback pattern:
function greet(name, callback) {
console.log("Hello, " + name);
callback(); // Execute callback
}
Example 2: Callback with Parameters
Pass data to callback:
function processArray(arr, callback) {
for (let item of arr) {
callback(item); // Pass item to callback
}
}
Example 3: Arrow Function Callbacks
Modern syntax:
arr.map(num => num * 2);
Example 4: Asynchronous Callbacks
Used with async operations:
setTimeout(function() {
console.log("Delayed execution");
}, 1000);
Example 5: Array Method Callbacks
Built-in array methods use callbacks:
forEach(): Iteratemap(): Transformfilter(): Selectreduce(): AccumulateExample 6: Error Handling Callbacks
Common pattern:
function fetchData(success, error) {
if (success) {
success(data);
} else {
error(message);
}
}
When to Use:
Callback Hell Problem:
Nested callbacks become hard to read:
func1(function() {
func2(function() {
func3(function() {
});
});
});
// Hard to read!Solutions:
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.