DEV Community

Cover image for JavaScript Callback Functions Explained: A Beginner's Guide
Ayush Sarodey
Ayush Sarodey

Posted on

JavaScript Callback Functions Explained: A Beginner's Guide

Introduction

If you're new to JavaScript, you might have heard the term 'Callback Function.' But what exactly is it? Why are Callback functions needed in JavaScript? Let's dive into it!

What exactly Callback Function is?

A Callback Function is function that is passed as a argument to another function , and it's executed after the completion of that function. This "parent" function can then execute the callback function at a certain point in its code, often in response to an event or an asynchronous operation. The primary purpose of a callback is to allow you to define custom behavior that should occur when a particular event or condition is met.

Now, What is Asynchronous Operation? An Asynchronous Operation is a task or process that doesn't block or pause the main program's execution while it's running. Instead, it allows the program to continue doing other things while it waits for the asynchronous task to complete.

Example

Let's illustrate this with a simple code example:

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

function sayGoodbye() {
  console.log("Goodbye!");
}

greet("John Doe", sayGoodbye);

Enter fullscreen mode Exit fullscreen mode

This code has two special functions: "greet" and "sayGoodbye." The "greet" function says hello to someone and then asks them to do something. In this case, it says hello to "John Doe" and asks him to say goodbye. The "sayGoodbye" function just says goodbye when it's told to. This code shows how in JavaScript, you can make one function tell another function to do something, which is useful for doing things in a specific order or handling events that happen at different times.

setTimeout Callback Function

setTimeout is a JavaScript function that allows you to schedule the execution of a specified callback function after a defined time delay, in milliseconds. This asynchronous feature is commonly used for tasks such as delaying the execution of code, creating timeouts for animations, or managing time-based events in web applications. When the designated delay elapses, the provided callback function is invoked, enabling you to perform actions or processes at a later time without blocking the main thread.

Syntax:

setTimeout(callback, delay);
Enter fullscreen mode Exit fullscreen mode
  • callback: A function that you want to execute after the specified delay.
  • delay: The time to wait (in milliseconds) before executing the callback function.

Basic Example:

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

setTimeout(greet, 2000, "John", "Hello"); 
// Calls greet("John", "Hello") after a 2-second delay

Enter fullscreen mode Exit fullscreen mode

In this example, the greet function is called with "John" and "Hello" as arguments after a 2-second delay.

Error handling with callback function

Error handling with callback functions is a common practice in asynchronous programming, especially in languages like JavaScript and Python. Callback functions are used to handle the results of asynchronous operations, and error handling is an essential part of ensuring that your code can effectively deal with unexpected problems, this is a crucial part of making it strong and dependable.

Syntax:

function callback(err, result) {
  if (err) {
    console.error("An error occurred:", err);
    // Handle the error, e.g., log it or notify someone
  } else {
    // Handle the result
  }
}
Enter fullscreen mode Exit fullscreen mode

Basic Example:

function divide(a, b, callback) {
  if (b === 0) {
    // Handle the error when dividing by zero
    callback(new Error("Division by zero is not allowed"), null);
  } else {
    // Perform the division and provide the result
    callback(null, a / b);
  }
}

// Usage
divide(10, 2, (err, result) => {
  if (err) {
    console.error("Error:", err.message);
  } else {
    console.log("Result:", result);
  }
});

divide(10, 0, (err, result) => {
  if (err) {
    console.error("Error:", err.message);
  } else {
    console.log("Result:", result);
  }
});

Enter fullscreen mode Exit fullscreen mode

The given code defines a divide function that takes two numbers, a and b, and a callback function. It checks if b is zero and if so, invokes the callback with an error message, indicating division by zero is not allowed. If b is non-zero, it calculates the division result a / b and passes it to the callback along with a null error. The code then demonstrates the use of this function by calling it twice, once with valid inputs (10 and 2) and once with an invalid input (10 and 0), handling and logging errors or results appropriately in each case.

Conclusion

To sum it up, callback functions are really important in modern programming. They help us write code that's flexible, efficient, and adaptable. So, when you come across a callback function, see it as a helpful tool to make your code look great, work well, and be responsive.

Top comments (0)