Let's Understand Callback

what exactly the callback is?

Table of contents

No heading

No headings in the article.

So What is the Callback?

  • Callback is a function(let's say function A) that is passed as an argument to another function (function B), which gets executed/called inside function B.

  • In JavaScript internally functions are objects, so they can be passed as an argument to a function and can be returned by a function.

  • Because of this ability the functions are called higher-order functions which can accept & return functions.

What is the Use of callback?

  • Callback is generally used for asynchronous operations in javascript

  • It follows "initiate now and execute later approach"

  • Callback is also used for tracking the status of a function

  • A callback can be used at one or two-level deep nesting not more than that. it becomes hard to read the code and maintain the code in chaining format.

  • JavaScript is Synchronous by nature, it executes tasks immediately as soon as they are called in the program. if there is a function that would take some time to execute and we have already defined other functions in the program, then JS will not wait for the function to get completed, it will directly run the consecutive functions

const doHomeWork = (subject, callback)=> {
    console.log("Ram Ram Bhai i have been executed")
    alert(`started my ${subject} subject`)
    callback()
}

const finishedHomeWork = ()=> alert("Finsihed my HomeWork")


doHomeWork("JavaScript", finishedHomeWork)

example no 2

const greeting = (name)=>alert(`Hello ${name}`)

const sayHello = (callback)=> {
    let name = prompt("Enter Your Name")
    callback(name)
}

sayHello(greeting)

in the examples above we can see we are passing the greeting function as an argument and the greeting function is called inside the sayHello function.

but wait why we are calling greeting inside sayHello? because before greeting we need to take the username with prompt as it becomes dependent on the user input so after getting the input greeting is called

example no 3

const printAfterDelay = (msg, delay, stop, stopDelay) => {
  let intervalId = setInterval(() => console.log(msg), delay);
  setTimeout(() => stop(intervalId), stopDelay);
};

const stop = (intervalId) => {
  console.log("clear Interval");
  clearInterval(intervalId);
};
const stopDelay = 8000; // ms
const msg = "Hare Krishna Hare Rama";
const msgDelay = 2000; //ms

printAfterDelay(msg, msgDelay, stop, stopDelay);

So that was a brief introduction to callbacks, to understand it better practice more examples, more use case.

Thanks For Reading 🥳