In this lesson we will talk about JavaScript callback functions, which are functions that are passed as parameters to other functions.

In the JavaScript version ES5 they are widely used, while in the ES6 they leave room for the promises that have become a native component of the language. A few years ago, in fact, the promises were used only thanks to external libraries.

Callback functions derive from a programming paradigm known as functional programming.

It is also good to remember that when we pass a callback function as an argument to another function, we are not executing the function, but we are only passing the definition of the function. So we don’t have to use round brackets, as we do when we execute a function instead.

JavaScript callback – first example

In this first example we will use a simple function for the sum of two numbers and then we will pass it as a parameter to another function.

So here is the code of our function which simply takes 2 numbers and returns their sum:



function sum(a,b){
  return a + b;
}

The function to which we will pass our function as an argument, therefore without brackets we will call it callsCallBack simply to make it clear that it calls a callback function.



function callsCallBack(callback){

  var number1 = parseInt(prompt('Insert a first number '));
  var number2 = parseInt(prompt('Insert a second number '));

  alert(callback(number1,number2));

}

Now let’s call the function:



callsCallBack(sum);

If you try the script you will notice that an alert will appear where the sum of the two numbers taken as input will be visible. If you prefer, use the console.log()!

JavaScript callback – second example

In this second example we will create an evenOdd function that returns true if a value passed as an argument is even, otherwise it returns false.

After our function callsCallBack we will pass a number and the function just created as arguments, without brackets. If the number passed is even we will print the string ‘even number’, otherwise we will print ‘odd number’.



function evenOdd(item) { 
  //function which will then be passed as an argument without brackets
  if (item % 2 == 0){
    return true;
  } else {
    return false;
  }
}

function callsCallBack(x,callback){ 
    //the parameters are a number and a function
    if (callback(x)) {
      console.log('even');
    } else {
      console.log('odd');
    }
    return x;
}


for (var i = 0; i < 10; i++){
  var n = parseInt(prompt('insert a positive number'));
  var y = callsCallBack(n,evenOdd);//I call the function without brackets
  console.log(y);
}

JavaScript callback – third example

In this third example we will populate an array of only numbers greater than or equal to zero (we discard only the negatives), again using the callback functions.

Then we create our positiveNegative function which returns a Boolean value.
Then we create the myArray function to which we pass a number, an array and a function as an argument (so I remind you without brackets), and we add the element to the array only if it is positive. This function returns our array.

Banner pubblicitario

Finally, through a for loop we ask for a number and call the popolaArray function with our parameters.

If we do the console.log() we can see our array populated with only numbers greater than or equal to zero.



function isPositive(item) { 
  if (item >= 0){
    return true;
  } else {
    return false;
  }
}

function myArray(x,array,callback){ 
    //where the parameters are a number, an array and a function
    if (callback(x)) {
      console.log('positive number - put it in the array');
      array.push(x);
    } else {
      console.log('negative number - don't put it in the array');
    }
    return array;
}

var numbers = [];

for (var i = 0; i< 10; i++){
  var n = parseInt(prompt('insert an integer number'));
  var y = myArray(n,numeri,isPositive);
  //I call the function without brackets
  console.log(y);
}
console.log('array: ' , numbers);

Conclusion

In this article we have seen some simple examples of using JavaScript callback functions, in the next lessons I will propose many other practical examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts