JavaScript Callback Functions

JavaScript Callback Functions

In JavaScript, a callback function is a function that is passed as an argument to another function and is executed inside that function. Callback functions are commonly used in asynchronous programming to handle responses to events, such as user actions or server responses. In this way, they allow for more flexible and dynamic programming.

To illustrate how callback functions work in JavaScript, let's take a look at some examples.

Example 1: Simple callback function

In this example, we define a function greeting that takes two arguments: a name parameter and a callback parameter. Inside the greeting function, we log a greeting message to the console with the name argument, and then call the callback function.

We also define another function sayGoodbye that logs a goodbye message to the console. Finally, we call the greeting function with the arguments 'Alice' and sayGoodbye as the callback function. The output of this code will be:

Hello Alice

Goodbye!

Example 2: Using callback function for asynchronous programming

In this example, we define a function getUserData that simulates a delay of one second using setTimeout, and then returns a user object with some data. This function also takes a callback function as an argument, which is executed with the userData object as the argument.

We also define another function displayUserData that logs the userData object to the console. Finally, we call the getUserData function with the argument 123 and the displayUserData function as the callback.

The output of this code will be:

Note that the console.log statement that prints 'Fetching user data...' is executed before the callback function is called, because the getUserData function simulates a delay of one second. This illustrates how callback functions can be used for asynchronous programming in JavaScript.

Overall, callback functions are an important concept in JavaScript that allow for more flexible and dynamic programming. They can be used for a wide range of purposes, including handling user input, making API requests, and performing other tasks asynchronously.

That's it for callback functions. Thanks for learning ❤️