What is callback function?

In JavaScript, a callback function is a function that is passed as an argument to another function and is intended to be called back or invoked later on, usually after some operation is completed or some event is triggered.

Callback functions are a fundamental concept in asynchronous programming in JavaScript, and they are often used to handle the result of asynchronous operations such as network requests, file I/O, or user input.

In this example, we have a function called doSomethingAsync that takes a callback function as an argument. The doSomethingAsync function simulates an asynchronous operation by using the setTimeout function to wait for 1 second before returning a result of 42 via the callback function.

We then call the doSomethingAsync function and pass in an anonymous function as the callback. This function takes the result as an argument and logs it to the console.

function doSomethingAsync(callback) { 
     setTimeout(() => { 
          const result = 42; 
          callback(result); }, 
     1000); } 

doSomethingAsync((result) => { 
     console.log(`The result is ${result}`); 
});

// Output: 

// The result is 42The result is 42

In this example, we have a function called doSomethingAsync that takes a callback function as an argument. The doSomethingAsync function simulates an asynchronous operation by using the setTimeout function to wait for 1 second before returning a result of 42 via the callback function.

We then call the doSomethingAsync function and pass in an anonymous function as the callback. This function takes the result as an argument and logs it to the console.

This demonstrates how the callback function is called back later, after the asynchronous operation is completed. Callback functions can also be used with other asynchronous operations, such as promises or event listeners, to handle the result of the operation.

Resources: 

Web Design Berlin - Cantour.es

Recent Posts

Web Design, Development & WordPress in Berlin