What is Javascript Callback and how to write your callback function!

Jam
2 min readAug 31, 2020

What is a callback function?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

Here is a quick example:

function greeting(name) {alert(‘Hello ‘ + name);}function processUserInput(callback) {var name = prompt(‘Please enter your name.’);callback(name);}processUserInput(greeting);

[ Source: https://developer.mozilla.org/en-US/docs/Glossary/Callback_function ]

Why and when we should use callbacks?

The above example is an asynchronous callback, as it is executed immediately.

Let’s think of a different scenario. Suppose:

  1. We want to get data from a backend server and,
  2. when we get success response, we want to use this response data

Example without a callback:

function get_product_info() {

$.ajax({

--

--

Jam

Software engineer | Full Stack Developer | Programmer | Designer & Entrepreneur