DEV Community

Maggie DeSantis
Maggie DeSantis

Posted on • Updated on

Writing flexible code - callback functions.

Today, I'd like to share a simple example of how callback functions can be used in JavaScript to perform an operation asynchronously and handle the result when it's available.

A callback function is a function that is passed as an argument to another function and is executed at a later point in time.

Let's say you have a function called 'add' that accepts two numbers and a callback function. Inside the 'add' function, you add the two numbers together and pass the result to the callback function.

To use the 'add' function with a callback, you simply call it with the numbers you want to add and a function that handles the result. For example, you could call 'add(2, 3, callback)' with a function that logs the result to the console.

When the 'add' function is executed, it calls the function with the result of the addition, allowing you to handle the result in a separate piece of code. This is a powerful programming concept that can make your code more efficient, flexible, and maintainable.

function add(a, b, callback) {
  const result = a + b;
  callback(result);
}

add(2, 3, function(result) {
  console.log(result);
});
Enter fullscreen mode Exit fullscreen mode

I hope this example helps you understand how callback functions work in JavaScript. If you have any questions or feedback or even want to critique a little, PLEASE leave me a comment, I'm still learning and love hearing others thoughts and better ways to work.

2/100

Top comments (0)