JavaScript: The React Parts

Callback Function

In JavaScript, when we want to create a block of reusable code, we create a function.


The example above shows how we can create a block of reusable code with different data (different value of number parameter). But is it possible to create reusable code with different behavior?

Let's consider the code below:


There are many duplications between the computation of doubleNumbers and biggerNumbers, but how do you create a reusable function that able to have slightly different behavior (* 2 and + 2)?

Enter callback function:


Thanks to the fact that function is first class in JavaScript, we can pass function as parameter. With that, we can create a function that has different behavior based on the function parameter.

This function that you pass to another function is usually known as callback function, due to the fact that that function will be "callback"ed by the function you call.

Besides creating JavaScript function with dynamic behavior, callback function is also a common pattern in asynchronous programming.


There is no comment on this post yet.

Issue on this page? Report here