Introduction

Callback functions are a powerful concept in JavaScript, allowing for asynchronous programming and better control over code execution in JavaScript.

A callback function is a function that is passed as an argument to another function and is executed after some operation has been completed. Callbacks are essential for handling asynchronous tasks, such as API calls, file reading, and event handling.

Synchronous Callbacks

Synchronous callbacks are executed immediately after the operation they're passed to completes. These are typically used with array methods like forEach, map, and filter.

Example:

function greet(name) {
  console.log(`Hello, ${name}!`);
}

function processUserInput(callback) {
  const name = prompt("Please enter your name.");
  callback(name);
}

processUserInput(greet);

In this example, greet is a callback function passed to processUserInput. When processUserInput is called, it prompts the user for their name and then calls greet with the user's input.

Asynchronous Callbacks

Asynchronous callbacks are used in operations that take time to complete, such as network requests, timers, and file reading. They allow other code to run while waiting for the asynchronous operation to finish.

Example:

console.log('Before setTimeout');

setTimeout(function() {
  console.log('This is a callback function.');
}, 2000);

console.log('After setTimeout');

Output:

Before setTimeout
After setTimeout
This is a callback function.

In this example, the callback function inside setTimeout is executed after a delay of 2 seconds, allowing the rest of the code to run first.

Handling Asynchronous Operations

Callbacks are commonly used to handle asynchronous operations, especially before the introduction of Promises and async/await.

Example: