The callback functions are used in JavaScript to ensure that the code is asynchronous, i.e. executed after a certain event, such as when a button is clicked, or when you pass over an element of the html page, etc.

We have also seen in previous articles that callback functions can be passed as arguments to functions, as they are objects.

In this article we will give some more examples to better understand their use.

In fact, their use with other predefined methods is interesting, as in the first example below.

callback functions – first example

We remove the odd elements from a previously populated array.

First let’s create our array of numbers.

Banner Pubblicitario

Next we create an anonymous function in JavaScript which we store in a variable number.

So in the variable number we are storing our callback function, which represents our object.

Then we filter the array using the filter method which invokes our callback function in Javascript, which was created to return true if an element is even.

The callback function takes a single parameter that represents each single element of the array that must be evaluated.

Then the function is called without round brackets within the filter method.



var array = [5,7,8,9,10];

var number = function(n) {
  if(n % 2 == 0){
    return true;
  }
};

//number becomes the function that I can call, therefore:
var num = array.filter(number);
console.log(num);

The console.log will print the array with only even numbers.

Therefore, the same function can also be written like this:

Banner pubblicitario


var array = [5,7,8,9,10];

var n = array.filter(function (n) {
  if(n% 2 == 0){
    return true;
  }
});

console.log(n);

callback functions – second example

We insert 5 numbers in an array at the click of the button and then display their sum.

Also in this case we use an anonymous callback function within which we call the functions askNumbers and sumNumbers.

The AskNumbers function takes an array and the quantity of numbers to insert as arguments, while the AddNumbers function takes the array as an argument.



var numbers = [];

var calculation = document.getElementById('calculation');

calculation.addEventListener('click',function (){
  insertNumbers(numbers, 5);
  var sum = sumNumbers(numbers);
  alert('Sum is: ', sum);
});


function insertNumbers(arr, q){
  while (arr.length < q){
    var n = parseInt(prompt('Insert a number));
    arr.push(n);
  }
  return arr;
}

function sumNumbers(array){
  var sum = 0;
  for (var i = 0; i< array.length; i++){
    sum += array[i];
  }
  return sum;
}

Conclusion

We have done some exercises on callback functions in JavaScript, in the next lessons we will return to this topic.

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