JavaScript Callback Functions - Step by Step

What is a Callback Function?
A callback function is a function passed as an argument to another function and is executed after the completion of that function.

See the step-by-step examples below. Output is shown for each step.

Step 1: Simple Function (No Callback)

function greet(name) {
  return 'Hello, ' + name + '!';
}
let result1 = greet('Alice');

This is a regular function. It just returns a greeting string.

Step 2: Function That Accepts a Callback

function processUserInput(name, callback) {
  return callback(name);
}

This function takes a name and a callback function, and calls the callback with the name.

Step 3: Passing a Named Function as Callback

function sayGoodbye(name) {
  return 'Goodbye, ' + name + '!';
}
let result2 = processUserInput('Bob', sayGoodbye);

Here, sayGoodbye is passed as a callback to processUserInput.

Step 4: Passing an Anonymous Function as Callback

let result3 = processUserInput('Charlie', function(name) {
  return 'Welcome, ' + name + '!';
});

An anonymous function is passed directly as a callback.

Step 5: Passing an Arrow Function as Callback

let result4 = processUserInput('Diana', name => 'Hi, ' + name + '!');

An arrow function is passed as a callback for concise syntax.