WDD 131: Dynamic Web Fundamentals

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.

"A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action." - MDN Web Docs
Course Learning Outcomes
  1. Demonstrate proficiency with JavaScript language syntax.
  2. Use JavaScript to respond to events and dynamically modify HTML.

Prepare

Activity Instructions

Given these function declarations:

function calculate(a, b, callback) {
  callback(a + b);
}

function displayResult(result) {
  console.log('The result is: ' + result);
}

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.