Callbacks in Javascript

Callbacks in javascript photo.

Before diving into callbacks, we have to understand that, in javascript, functions are first-class objects. As such, we can dynamically create, destroy, pass to a function, return as a value a first-class object. Also, it has all the rights as other variables in the programming language have.

Callbacks in Javascript

If we pass a function as an argument to another function, we call it a callback function in javascript. A higher-order function takes the function argument. For example, the following lines of code illustrate a callback function.

let arr = [1, 5, 10, 8, 4];

function displayValue(value, index) {
  console.log(`arr[${index}] = ${value}`);


As we know from the documentation, forEach method of an array takes a callback function with parameters currentValue, currentIndex, and self array. In the example above, we defined a function displayValue, which has the first two parameters of the callback function. So, in this example, we performed the operation defined in displayValue function for each item of the array. Now, let’s create our own functions with a callback.

function takeInput(cb) {
  let x = prompt("Enter number1: ", 0);
  let y = prompt("Enter number2: ", 0);
  let operator = prompt("Enter operator (+, -, *, /): ", '+');
  cb(+x, +y, operator, showResult);

function calculate(x, y, operator, cb) {
  switch (operator) {
    case '+':
      cb(null, x + y);
    case '-':
      cb(null, x - y);
    case '*':
      cb(null, x * y);
    case '/':
      if (y === 0) {
        cb(new Error('Cannot divide by zero.'));
      cb(null, x / y);
      cb(new Error('Unidentified Operation.'));

function showResult(err, result) {
  if (err) {


As we can see in the example above, first of all, we have to take inputs of two numbers and an operator. Then, we passed the input values to a callback function. Again, the function takes another callback showResult which displays the results. Since, takeInput takes a callback function, we pass calculate function as callback. That is, when we finish the process of taking input, the calculate function is called with arguments. Furthermore, the calculate function also takes a callback function showResult as mentioned above. Similarly, the showResult function takes two arguments err and result. If there are any errors, we pass them as the first argument, otherwise we pass null. The second argument takes the result.

The following link is from Mozilla Developer Network (MDN), which give another example of callback function.

I hope, you get a clear understanding of callbacks in javascript. If you want to know something more about JSON, you can follow this link.

0 0 votes
Article Rating
Notify of
1 Comment
Newest Most Voted
Inline Feedbacks
View all comments