DEV Community

kelseyroche
kelseyroche

Posted on

Callback Functions

Sharpay Callbacks gif

Is learning about callback functions making you feel just like Sharpay?

Well, before we get into the technical stuff let's think about it in a more theoretical way: with cake! 🎂

Imagine you want to bake a cake for your friend's birthday. The day before their birthday you follow a recipe for the icing and put it in the fridge to sit overnight. Here, the recipe for the icing is the callback function. You're not using the icing yet, but it's waiting to be called on later!

The day of the birthday party you decide to pull up the cake recipe. It calls for flour, water, eggs, sugar, baking powder, salt, milk, and icing.

This recipe, or function, is using a bunch of variables and also that recipe, or function, for icing. It's calling back on that recipe you already created, or declared, earlier.

Ok enough about cake (sadly), let's get into the technical stuff:

At this point we are used to passing variables as arguments in a function. In Javascript, we can also use functions to pass as arguments in a new function. The first function is the callback function and that is the one being passed as an argument through the new function.

For example:

//callback function
function icing ( ) {
console.log("vanilla icing")
}

//new function
function cake (flavor, callback) {
console.log("My cake flavor is " + flavor);
callback();
}

//using the callback function as an argument
cake ("pumpkin", icing);

What do you think the result is here?

At the bottom of the code you can see that we called the cake function. Because we are passing through "pumpkin" as the first argument, we know that the console is going to log "My cake flavor is pumpkin"

The second part of this function uses the second parameter to call that function. When we are calling cake, we see that the second parameter we are calling is the icing function. The icing function wants us to console.log "vanilla icing."

Therefore, our console should read:

My cake flavor is pumpkin
vanilla icing

And there is our recipe for the callback function, enjoy!

Cake with code on it in icing

Extra Challenge:
Try writing a function called decorate that takes a callback function to add decorations to a cake!

Other Materials:

https://www.programiz.com/javascript/callback
https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

Top comments (2)

Collapse
 
link2twenty profile image
Andrew Bone

Just a heads up that you can add code blocks if you'd like.

code block with no colors example

... to specify the language:

code block with colors example

More details in our editor guide!

Collapse
 
kelseyroche profile image
kelseyroche

thank you this is super helpful!