Javascript Callbacks - Meteorio

Javascript Callbacks

| 4 years ago

One fine morning your mom tells you something.

“Listen! once you are done with your breakfast, make sure you fill up every empty water bottle and put them in the refrigerator “.

So basically you have been asked to do something once something else is done.This is how callbacks work.

Example

Output
Mom! i am having my breakfast
Mom! i have filled up the water bottles

When to use Callbacks?

Javascript callbacks are mostly used while handling asynchronous calls like calling an API, reading or writing into files etc . In other words we use callbacks when we have some time taking operations and we are dependent on completion of the operation.

Callback definition

Functions are first-class objects in javascript and can be passed as an argument to another function. A callback, sometimes also refered as High order function can be defined as a function that can be passed to another function as an argument and later can be executed or returned to be executed inside the other function.

Passing arguments into callbacks

In some cases, we will need to pass arguments to the callback function. Let’s see an example

Example

Output
The result is - 25

Callback hell

When you have callback inside a callback inside another callback and so on, then the code is quite difficult to read aswell as messy. This condition is known as Callback hell. Let’s look at an example code with Callback hell

Well ! Callback is widely used by javascript developers but using multiple callbacks can result into Callback hell and thus should be avoided in such cases.

I hope you have a better understanding of Javascript callbacks by now. I would love to have some discussions and answer queries if any. If you have anything to say , you have the comments section for you.

Happy Coding !!!!!

References

1. https://developer.mozilla.org/en-US/docs/Glossary/Callback_function.
2. https://en.wikipedia.org/wiki/Callback_(computer_programming).

Adverts *