Callback Function in JavaScript - Veltris

Callback Function in JavaScript

December 23, 2020 | Mohammad Yasir

    Callback Function:

    When we call a function , we may pass some data as an arguments to that function like 1,2,”Car” etc,But in JavaScript , it is possible to pass a function as an argument to that function as well.

    These Function are called callback function.So it’s the parent function(the function in which callback function is passed as an argument),will call this function in it’s body when required.

    Let’s understand this with code example.

    function parentFunction(childFunction){
      //Other's code in the body
      childFunction();
    }
    function childFunction(){
      //function body
    }
    parentFunction(childFunction)// calling parentFunction & passing the childFunction as callback function

    Here in above example the function “childFunction” is used as callback function,And the function “parentFunction” is calling this callback function in it’s body.

    One thing also need to notice here that, the function Which take a function as parameter are called high order function. So it this example the function “parentFunction” is a high order function which is taking “childFunction” as a parameter.

    Examples of callback we frequently use :

    If you know the basic of JavaScript, You probably have used filter,map,findIndex etc. of array in JavaScript. So these all function takes another function as a parameter.

    Now let’s talk about filter function, it will call your function that you passed with n times(n= length of array),And its return an filtered array, Which includes the items for which your function returns true.

    Also filter,map,findIndex etc are high order function order function because they all take a function as a parameter.

    Conclusion:

    From above explanations, it clear that when a function as passed as an argument in another function are called callback function, And when a function receive another function as a parameter are called high order function.

    Related Articles