Callback Functions in JavaScript Over-Simplified

Callback Functions in JavaScript Over-Simplified

ยท

7 min read

Introduction

Callback function is a term used a lot by computer programmers and one has to dig deep to understand it.

If you find it weird, I've made this blog to break it to pieces & increase your knowledge about it.

Let's learn like a 5 year old.

Prerequisites

To understand this blog, you need to have this:

  • A basic understanding of HTML as we will be using it to show some examples.
  • Basic understanding about JavaScript functions
  • Familiar with Web Development syntax
  • Let's start learning. ๐Ÿš€

    I almost used this image as the first picture while writing this blog.

    istockphoto-1289834579-170667a.jpg

    She missed a call and was trying to call the person back! ๐Ÿ˜น

    Related right?

    Okay, let's learn.

    Functions:

    Quite familiar with functions in programming languages?

    It is a block of code telling a computer to do something.

    Something like this:

    function multiply(a, b) {
      return a * b;             
    // This function returns the product of a and b
    }
    // a & b are parameters
    
    let x = multiply(4, 3);   
    
    // x is declared, a function is stored in it. 
    // The function returns the product of 4 & 3 and stores the result in x.
    
    // 4 & 3 are arguments
    
    // x = 12
    

    Here, when the function is called, it multiplies the arguments and returns the result to x.

    The arguments are 4 & 3, the parameters are a & b.

    If you want to learn more about JavaScript functions, I've written a blog about it here.

    We have seen how arguments are used. Parameters are the names used when defining function while arguments are the real values passed to the function. Parameters are initialized to the values of the arguments given.

    Here is a quick way of how a parameter and argument works.

    function example(parameter) {
      console.log(parameter);
    }
    
    const argument = 'Hello World!!!';
    
    example(argument); // Output = Hello World!!!
    

    Clear?

    Now let's talk about a Callback function.

    What is a Callback Function?

    A Callback function is a function passed as an argument to another function.

    Let us take an example:

    We have two functions, function a & function b. When function a is called, function b is passed into it as an argument.

    Here is an example:

    function b(parameter){
     // block of code
    } // function b is defined
    
    function a(parameter1, parameter2, b){
    // block of code
    b(argument) // function b is called
    } // function a is defined
    
    a(argument1, argument2, b);
    // function a is called here
    

    While defining function a, the callback can have any name but should match the name used in the function.

    Here is an example, in the above code, you can still define function a this way and nothing breaks.

    function a(parameter1, parameter2, c){
    // block of code
    c(argument)
    };
    
    a(argument1, argument2, b);
    // function a is called with b as the callback function
    
    // b maps to c
    

    This technique allows function a to call function b. Function b is the Callback function.

    A Callback function will run in another function (function b will run immediately after function a because function b is called inside function a).

    You may wonder why we even need a callback function in the first place.

    Why Callback functions?

    Why do we need a function to call another function? Why do we need function a to call function b?

    Or are we calling function a to call function b? Is this just a shortcut?

    No.

    Remember that JavaScript functions are executed in the sequence that they are called and not as they are defined.

    Here is an example:

    function firstDefined() {
      console.log("Hello");
    }  
    
    //firstDefined is defined first
    
    function secondDefined() {
      console.log("Goodbye");
    }
    
    secondDefined();  // secondDefined is called first
    firstDefined();
    

    The above example will display "Goodbye" to the console before "Hello" even though ''Hello'' is defined first. The reason is because secondDefined() is called first.

    Callback functions are used where function x has to wait for function y to run before function x executes because function x needs a value from function y.

    Practical example of function

    Without callback function

    If we want to multiply two numbers and display the answer to our HTML when the answer is ready, here is how we will do it without callback functions.

    <p> 10 x 2 = <span id="demo"></span></p>
    <button onClick="display(answer)">Calculate</button>
    
    <script>
    function display(result) {
      document.getElementById("demo").innerHTML = result;
    }
    
    function calculate(num1, num2, display) {
      let product = num1 * num2;
      return product
    };
    
    let answer = calculate(10, 2);
    
    </script>
    

    Here, we called a display function with answer as an argument. answer is a variable that stores a function calculate that multiplies 10 and 2. The result is 20 and stored in the answer variable. Thus, in the button, 20 is passed as an argument and maps to display function. 20 maps to the result parameter and then show the result in the HTML.

    There is a problem here anyway, we have to call two functions to display the result. We called calculate and display functions.

    Here is another way to do that without using callback function.

    <p> 10 x 2 = <span id="demo"></span></p>
    <button onClick="calculate(10, 2)">Calculate</button>
    
    <script>
    function display(answer) {
      document.getElementById("demo").innerHTML = answer;
    }
    
    function calculate(num1, num2) {
      let answer = num1 * num2;
      display(answer);
    };
    </script>
    

    Here, we called function calculate to multiply 10 and 2, the result is gotten and passed as an argument into the display function. The problem with this is that we cannot prevent the calculate function from displaying the answer.

    With callback function

    After getting the product of 10 and 2, we want to update a p tag to show the result using a callback function and without calling two functions.

    <p> 10 x 2 = <span id="demo"></span></p>
    <button onClick="calculate(10, 2, display)">Calculate</button>
    
    <script>
    function display(answer) {
      document.getElementById("demo").innerHTML = answer;
    }
    
    function calculate(num1, num2, display) {
      let product = num1 * num2;
      display(product);
    };
    
    </script>
    

    With the button is clicked, calculate function is called. It has 3 arguments which are 10, 2 and display.

    The callback function is display because it will be run in the calculate function.

    The 'calculate' function multiplies the first two arguments 10 & 2 and store the result as product which is passed as an argument for the callback function named display.

    Note that display in the calculate function can be written as anyOtherWord and nothing breaks because it is a parameter when the calculate function is defined.

    function calculate(num1, num2, anyOtherWord) { 
    // anyOtherWord is a parameter here
      let product = num1 * num2;
      anyOtherWord(product);
    };
    

    When the button is clicked and calls calculate function with onClick="calculate(10, 2, display)", display is mapped to anyOtherWord.

    We defined the display function before the calculate function, but the display function is called in the calculate function after the result of the calculation is gotten.

    function display(answer) {
      document.getElementById("demo").innerHTML = answer;
    } // display function is defined here
    
    function calculate(num1, num2, display) { 
    // num1, num2, display are parameters here
      let product = num1 * num2; 
    // result of the calculation is gotten here and stored to product
      display(product); 
    // display function is called here with product as argument
    };
    

    JavaScript will parse 10 & 2 into calculate function assigning num1 to 10 and num2 to 2, the result is stored in product variable before passing product as an argument into display function.

    Note that when you pass a function as an argument, do not use parenthesis.

    Correct:

    <button onClick="calculate(10, 2, display)">Calculate</button>
    

    Wrong:

    <button onClick="calculate(10, 2, display())">Calculate</button>
    

    This blog is simplified to teach you the basics of callback syntax. Callbacks are better used in asynchronous functions, where one function has to wait for another function.

    For example, a function has to wait for another function that loads a file or get a value using an API before passing the value or file in another function as arguments.

    Read more about asynchronous functions here

    Hopefully you'll find this blog helpful as you learn to code more effectively, and to know that there's a lot more to coding than write code.

    Before You Leave,

    If you enjoyed this article and want to see more content related to JavaScript and Web development, then follow me here, Twitter or connect on LinkedIn.

    I'd be happy to count you as one of my ever-growing group of awesome friends on the internet.

    If you also want to support me, you can buy a cup of coffee for me here.