DEV Community

Daniel Zaltsman
Daniel Zaltsman

Posted on

Callback Functions in Javascript

What is a callback function and why do we use them? The purpose of one is related to the asynchronous nature of Javascript and web programming. Before I dive a bit deeper, first let's go through a few examples.

Try to guess which result returns first:


function functionOne(){
    console.log(1);
}

function functionTwo(){
    console.log(2);
}

functionOne();
functionTwo();
Enter fullscreen mode Exit fullscreen mode

In this case, functionOne logs 1 in the console before functionTwo logs 2, in the exact order we would have anticipated.

But what happens if functionOne takes a bit longer than functionTwo? Try to guess what happens when we make functionOne wait a while before logging in the console:

function functionOne(){
    setTimeout( function(){
        console.log(1);
      }, 500 )
}

function functionTwo(){
    console.log(2);
}

functionOne();
functionTwo();
Enter fullscreen mode Exit fullscreen mode

And here is the result:

Image from Gyazo

Interesting, this time functionTwo's return came back first. But why? It's because Javascript did not wait to call the next function, it is still running functionOne in the background while also calling the next function. This makes knowing the exact order of our execution difficult. This is where a callback function comes into play.

What is a Callback Function?

Callback functions(also called "higher order functions") are functions that take in a function as an argument. It's a way to control the order of execution, to make sure the right functions are running at the time you need them to.

Let's take a look at an example:



function eatfruit(fruit,callback){
    console.log(`This is a delicious ${fruit}`);
    callback();
}

eatfruit('strawberry', function(){
    console.log('I think I would like another')
})

Enter fullscreen mode Exit fullscreen mode

Image from Gyazo

When defining the eatFruit function, we pass in a function as an argument and call it after the first console.log. As expected, the console shows 'This is a delicious strawberry' before the anonymous function runs. We can(and should) dry this even more by defining the anonymous function.



function eatfruit(fruit,callback){
    console.log(`This is a delicious ${fruit}`);
    callback();
}

function fruitGlutton(){
    console.log('I think I would like another')
}
eatfruit('strawberry', fruitGlutton)

Enter fullscreen mode Exit fullscreen mode

Image from Gyazo

The results stayed the same with the drier code, and the order in which your functions run are more predictable.

Top comments (0)