DEV Community

Reilly Shofner
Reilly Shofner

Posted on

Understanding Callbacks in JavaScript - From A Beginner For Beginners

Have you ever struggled to understand a concept while learning JavaScript? As a software engineering student at Flatiron School, I’ve been there too. In this post, I’ll break down a JavaScript feature that initially caused me a lot of confusion, callback functions.

Callbacks

Callbacks are a fundamental concept in JavaScript that can seem confusing at first, but they're actually quite straightforward once you grasp the basics. In this article, I will explore what callbacks are, why they're important, and how they are used in JavaScript.

What is a Callback?

When I first started learning JavaScript, I found it confusing that people referred to callback functions as both callbacks and callback functions. Understanding the technical vocabulary in programming can be overwhelming at times, especially if your brand new to coding. It’s important to remember they are the same thing so as to not cause any unnecessary confusion. In JavaScript, a callback function is simply a function passed as an argument to another function to be executed later. I like to think of it as a placeholder that represents a reference to a function to be executed later.

Here's a simple example to display this concept:

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

greet("Reilly", function() {
    console.log("Greeting completed."); //OUTPUT: Hello, Reilly!
});                               //CALLBACK OUTPUT: Greeting completed.
Enter fullscreen mode Exit fullscreen mode

In this example, greet is the main function, and the second argument we pass to it is our callback function. The greet function does its thing (printing a greeting) and then calls our callback function which in turn notifies the console "Greeting completed".

Why Do We Need Callbacks?

Callbacks are particularly useful in JavaScript because they allow us to write asynchronous code. Asynchronous code is code that doesn't necessarily run in sequence. Callbacks allow your code to keep running while it waits for something else to happen, like downloading data from the internet or reading a file from disk.

Types of Callbacks

There are two main types of callbacks: synchronous and asynchronous.

-Synchronous code definition: Tasks are executed one after the other. Each task waits for the previous one to complete before it starts.

-Asynchronous code definition: Tasks are executed independently, without waiting for the previous task to finish. This is useful for tasks like fetching data from a server or waiting for a timer.

Synchronous Callbacks

Synchronous callbacks are executed immediately within the calling function. JavaScript goes down your stack of code reading it in a sort of chronological order.

function doSomethingWithNumber(num, callback) {
    callback(num); // Call the callback function with the number
}

function checkNumber(num) {
    if (num === 2 || num === 4) {
        console.log(num); // Logs 2 or 4
    }
}

doSomethingWithNumber(2, checkNumber); // Output: 2
doSomethingWithNumber(4, checkNumber); // Output: 4
Enter fullscreen mode Exit fullscreen mode

Here the doSomethingWithNumber function takes a number(num) and a callback. We use checkNumber for the callback and is executed with the number as the argument. the checkNumber callback checks to see if the (num) is equal to 2 or 4 and if so it logs it to the console. The callback function is executed immediately when its called and run in sequence making this a synchronous callback.

Asynchronous callbacks

Asynchronous callbacks are typically used for operations that take time, like network requests or file operations. They allow your code to continue running while waiting for such tasks to complete, without blocking other parts of the program from running and executing. This way, multiple functions can run at the same time, and the order in which they finish doesn’t necessarily follow the order they were started.

function fetchData(callback) {
    setTimeout(() => {
        const data = "Data from server";
        callback(data);  // callback is executed after 2 seconds
    }, 2000);
}

console.log("Requesting data...");
fetchData((data) => {
    console.log(data); // This logs "Data from server" after 2 seconds
});
console.log("Request sent...");

//OUTPUT ORDER 1."Requesting data... 2. "Request sent..." 3. "Data from server"


Enter fullscreen mode Exit fullscreen mode

The fetchData() function starts but doesn't block the program. It waits for 2 seconds before invoking the callback with "Data from server", which is logged afterward. This makes it Asynchronous. First the console.log "Requesting data..." is read and output it then sees the callback for fetchData but has a setTimeout making it Asynchronous since it is not the next thing output, the next console.log "Request sent..." is immediately read and output, and finally after the 2 second timeout "Data from server" is output.

Best Practices for Using Callbacks

  • Keep it Simple: Avoid nesting too many callbacks. This can lead to what's known as "callback hell," which makes your code hard to read and maintain.

  • Use Named Functions: Instead of anonymous functions, use named functions for your callbacks. This makes your code more readable and easier to debug.

Conclusion

I hope this explanation of Callback functions from a beginner to a beginner proves helpful to anyone seeking clarity on the topic, especially those who may have found more technical jargon or complex examples difficult to understand.

Sources:
https://base.flatironschool.com/
https://www.w3schools.com/js/js_callback.asp
https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
https://www.youtube.com/watch?v=i2SPq-nb3NQ
https://www.youtube.com/watch?v=NOlOw03qBfw

Top comments (0)