JavaScript Callback Function

JavaScript Callback Function

ยท

5 min read

Callback function introduction

A callback is a programming concept where a function is passed as an argument to another function, with the intention that it will be called or executed at a later time.

This mechanism is often used in event-driven or asynchronous programming paradigms.

Above explanation may sound absurd if its the first time hearing about js callback function. Lets get started:

functions are a first-class-object in javascript - Don't let the vocabulary discourage you this simply means that functions have the same rights as any other datatype in javaScript. By now i know you're familiar with one writing code like this :

let num1=20;
let num2=num1;
console.log(num2) //output is 20

What we are doing is that we are taking the value of of num1 which is 20 and setting it to a variable so that we can reference it again and again. Therefore we can do something similar with a function. example:

let myFunction=function(){
console.log("i'm learning callbacks") 
}

The expression function above can do the same as how we did with variables num1 and num2. I mean we can add this to the code above

 let myFunction=function(){
console.log("i'm learning callbacks") 
} // addition to the above code ๐Ÿ‘‡
let myFunction2= myFunction // note here no paranthesis on myFunction
myFunction2() // calling my function2 // output is i'm learning callbacks

In the above code we are making a copy of myFunction. In such a way we can call our myFunction2.

NOTE:

I mentioned you should not add parenthesis on end of myFunction2 because adding parentheses would execute the function immediately and assign the result of the function call to the variable myFunction2. example :

Lets say we had a code to log out the statement "i finally ran!" using the setTimeout() method

function callback() {
    console.log("I finally ran!")}
setTimeout(callback, 2000)//outputs "i finally ran!" after 2sec 
//NOTE: NO parenthesis on the callback

if we include a parenthesis on the callback it will execute immediately without waiting for the 2 sec. TODO: Recall to do this with and without parenthesis on your console.

Callbacks in real projects.

callback taking one parameter.

Now that you have the basics of callbacks you can now work with callbacks in real projects: Example1:

With array of objects (people), a new array is crated with the .filter() array method that contains only the objects where "hasPet" is true

const people = [
    { name: "Jack", hasPet: true },
    { name: "Jill", hasPet: false },
    { name: "Alice", hasPet: true },
    { name: "Bob", hasPet: false },
]
const peopleWithPets = people.filter((person, index) => {    
}) //output will be [{name: "Jack", hasPet: true}, {name: "Alice", hasPet: true}]

Since we are working with callbacks, part two of this is to Move the anonymous in-line function to its own, named function. The code will look like this:

const people = [
    { name: "Jack", hasPet: true },
    { name: "Jill", hasPet: false },
    { name: "Alice", hasPet: true },
    { name: "Bob", hasPet: false },
]

function checkForPets(person) {
    return person.hasPet
}

const peopleWithPets = people.filter(checkForPets)
console.log(peopleWithPets)
//output will be [{name: "Jack", hasPet: true}, {name: "Alice", hasPet: true}]

If you're feeling unfamiliar with the array method .filter() be sure to checkout this JavaScript Tutorial .

Example2:

callback taking two parameters.

The below example takes two parameters:

  1. The array you want to filter through, and

  2. A callback function

* Steps for filterArray function logic:

  1. Initialize a new, empty array which will be returned at the end of the filterArray's operations

  2. Loop through the array passed as the 1st parameter

  3. Inside the loop, call the callback function, passing the individual item you're currently looping over as the argument to your callback function

  4. If the callback function returns true, push the current item you're iterating on in the loop to the new array. If it returns false, don't push it to the array.

  5. When the loop is over, return the new array

const people = [
    { name: "Jack", hasPet: true },
    { name: "Jill", hasPet: false },
    { name: "Alice", hasPet: true },
    { name: "Bob", hasPet: false },
]
//two parameters taken in ๐Ÿ‘‡ array and callback
function filterArray(array, callback) {
        //step1
    const resultingArray = []
    // filtering logic here step2
    for (let item of array) {
    //step3
        const shouldBeIncluded = callback(item)
        if (shouldBeIncluded) {
        //step4
            resultingArray.push(item)
        }
    }
//step 5
    return resultingArray
}

Use your filter array method!

* Given the above people array, return a new array with only people where hasPet is true

* Note: Remember that your callback function will be given the individual item in the array for a parameter

const people = [
    { name: "Jack", hasPet: true },
    { name: "Jill", hasPet: false },
    { name: "Alice", hasPet: true },
    { name: "Bob", hasPet: false },
]
//two parameters taken in ๐Ÿ‘‡ array and callback
function filterArray(array, callback) {
        //step1
    const resultingArray = []
    // filtering logic here step2
    for (let item of array) {
    //step3
        const shouldBeIncluded = callback(item)
        if (shouldBeIncluded) {
        //step4
            resultingArray.push(item)
        }
    }
//step 5
    return resultingArray
}
//step6
const peopleWithPets = filterArray(people, function(person) {
    return person.hasPet
})
console.log(peopleWithPets)
//output will be [{name: "Jack", hasPet: true}, {name: "Alice", hasPet: true}]

Conclusion

By mastering callback functions, you unlock the potential for efficient, scalable, and responsive code.

I really hope this article was helpful and has clarified about callback function. Spend as much time in this article and other tutorials to try and supplement it with you like google research and youtube tutorials.

Let me know your thoughts in the comment section and what suggested topics you would like to learn more about that I may cover. Happy coding!

ย