Callback Functions in JavaScript : Beginners

Subscribe to my newsletter and never miss my upcoming articles

In this latest post, we'll understand Callback function in JavaScript.

Callback function

=> It is a function that is passed as an argument to another function with the intention of calling it at a later time. In javascript, every function is a first-class object, which means that every function is an object and can be used like any other object(String, Number etc). This allows the use of a function as an argument in another function which is the fundamental idea of a callback function. > Note that when passing a callback function as a parameter to another function we are only passing the callback function definition.

Using anonymous functions as callbacks

setTimeout(function() {
       console.log("Logged after 1 second"); 
  }, 1000); 
    // Logged after 1 second

An anonymous function is a function without a name.

Using named functions as callbacks

const isOdd = (num) => {
   if ( num % 2 !== 0 ) {
       return num; 
   const nums = [2, 3, 44, 33, 55, 66, 3, 4, 959, 25]; 
   // isOdd as an argument in filter function
const oddNums = nums.filter(isOdd); 
  // [ 3, 33, 55, 3, 959, 25 ]

filter() is an array method which returns a new array including elements that pass a given condition in a callback function.

Learn in detail about filter() method

Using named functions as callbacks

Using names functions as callbacks has two advantages over using anonymous functions for callbacks:

  • It makes your code easier to read
  • Named functions are multipurpose and can be used on their own or as callbacks.

Callback functions can be asynchronous or synchronous

A synchronous callback function is invoked before functions returns.

The example earlier, where callback is passed in the filter function is an example of a synchronous callback.

An asynchronous or deferred callback is invoked after function returns, or at least on another thread's stack.

The example earlier, where callback is passed setTimeout() function is an example of a asynchronous callback.

Why you should use callback functions

  • Write more clean and readable code
  • Do not repeat yourself
  • Have better maintainability
  • Understand the use if many javascript libraries that are using callbacks.

Thanks For Reading.
Comment if you have something in mind.

No Comments Yet