DEV Community

Maggie DeSantis
Maggie DeSantis

Posted on • Edited on

1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay