DEV Community 👩‍💻👨‍💻

gcalvoCR
gcalvoCR

Posted on • Updated on

Callbacks in JavaScript. Let's break them down!

Callbacks are a simple concepts that many times confuse people when they are learning how to program.

Leaving aside that depending on the programming language the implementation could vary and there are synchronous callbacks (immediate) and asynchronous callbacks (may happen at a later time). Let's just focus on JavaScript.

Let's take the 3 following concepts:

  • First of all, the formal definition of a callback is

"is any executable code that is passed as an argument to other code that is expected to call back (execute) the argument at a given time"

  • In JavaScript you can assign functions to variables

  • JavaScript methods (functions) are first class objects, you can pass them around like variables

Knowing that, let's dive into an example to make it crystal clear.

Let's say that we define an execute method that receives a variable and a (callback) function.

function execute(px, callback){
    let x = callback(px)
    console.log(x);
}

I know, it's not necessary to instantiate the x

In this simple case, the callback function could be any function that has one parameter, so, let's define 2 more methods (functions) to test the execute method.

function squaredNumber(px){
    return px*px;
};

function numberPlusHundred(px){
    return px+100;
};

So, if we run:

execute(2, squaredNumber)

>>> The execute method will call squaredNumber(x) and the result would be 4

But if we run:

execute(2, numberPlusHundred)

>>> The execute method will call numberPlusHundred(x) and the result would be 102

It is as simple as that, using callback functions enable us to call different functions as needed making the programming even more flexible.

Final Thoughts

The given example could be way too simple but trust me, callbacks are used everywhere! To mention a couple of examples, Jquery and Ajax have them implemented in many methods. So, you should master the concept and take advantage of their benefits (Abstraction, Maintainability, Readability), and so on.

Any comments?

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.