JavaScript Callback Functions

JavaScript Callback Functions

If you are familiar enough to javascript , you must have heard javascript being termed as a asynchronous type of programming language. Asynchronous programming involves proper handlings of all the asynchronous operations being used in your project.One of the ways you do this is through usage of callback functions. So, in this post, I would like to help you to understand what callback functions are and how to use them in JavaScript by going through some examples.

In javascript , As told in my previous blogs, everything is treated as objects. In-fact the functions are also looked at under the same hood.

Can we pass objects as parameters to a function ? Yes

The same way we can pass functions as a parameter to another function. But an additional thing in this callback functionality is that, whatever the functions are passed in as a parameter to a different function, are called. Sounds Complicated ?

Let's Get To An Example:

function print(callback) {  
    callback();
} thi

The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function. But that’s not all.

Why do we need Callback Functions?

Consider that there are two functionalities viz A and B(Two functions named A and B). The functionality B is dependant on A. If A is buggy, then there is sure of bugs on B and may result in complete code faults. In these case, we can make usage of callbacks. Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.Here as B in dependant on A then the methodology with which you can solve this problem is we can pass A as a parameter and call A(callback) before B. Thus we can see no bugs and desired outputs.

Callback as an Arrow Function

If you prefer, you can also write the same callback function as an ES6 arrow function.

I hope this posts help you understand what callbacks is and what they actually do. But the Only thing which is necessary to excel this kind of topics is by doing practice.

Thank You For reading :)