Callback Functions
Overview
Callback functions are a powerful feature of JavaScript. They are used extensively in the JavaScript language and in the browser. Callback functions are used to handle events, to process data, and to control the flow of a program.
Course Learning Outcomes
- Demonstrate proficiency with JavaScript language syntax.
- Use JavaScript to respond to events and dynamically modify HTML.
Prepare
- Reference Callback Functions - MDN web docs
- Ponder this article demonstrating the use of callback functions: Callback with built-in functions - devgenius.io
Activity Instructions
Given these function declarations:
function calculate(a, b, callback) {
callback(a + b);
}
function displayResult(result) {
console.log('The result is: ' + result);
}
- Call a function named
calculate
and pass it the arguments to support the console output of the following equation:2 + 3
. You need to pass three arguments to thecalculate
function.Check Your Understanding
calculate(2, 3, displayResult)
A common example of a callback function is in JavaScript, particularly in asynchronous operations such as handling events or making async requests. Here is a simulated example:
function fetchData(callback) {
// using setTimeout to simulate fetching data from a server
setTimeout(() => {
// This calls the 'callback' function and passes data to it.
callback('Data has been fetched');
}, 2000); // This simulates a 2-second delay from a service.
}
// function that processes the data
function processData(data) {
console.log("Data received:", data);
}
// Call the fetchData function and pass the processData function as an argument.
fetchData(processData);
The fetchData function simulates fetching data from a server by using the setTimeout function to create a 2-second delay. After the delay, it calls the provided callback function, passing the string 'Data has been fetched' as an argument. In this context, the processData function is passed as the callback to fetchData, and it logs the received data to the console when called.