Callbacks →

  1. You will most probably never need callbacks when writing synchronous code
  2. Callbacks are used primarily in asynchronous architectures

<aside> 💡 In very simple words, Callbacks are functions that you can pass as an argument to another function or sub-routine in a program that will make your life easier and help you in writing less code

</aside>

function square(n) {
  return n * n;
}

function cube(n) {
  return n * n * n;
}

function sumOfSomething(a, b, callbackFunc) {
  return callbackFunc(a) + callbackFunc(b);
}

const a = 3;
const b = 7;
console.log(sumOfSomething(a, b, square));

Async Functions →

  1. Your JS doesn’t have access to anything and everything in the world. In fact, it doesn’t even have access to your file system directly, you’ll have to create a sub-routine for that, and since it’s not natively within the architecture, it usually takes longer than usual for it to access those “outside world” things.
  2. So does this mean that whenever we write a program, and we have a logic of let’s say “fetch the response from an API endpoint”, we wait for that logic to run before we can run the rest of the program?
    1. What if our rest of the program depends on that response?
    2. What if our rest of the program DOES NOT depend on that response?
    3. What if the operation of fetching response fails, because of xyz reasons?

That’s why, asynchronous functions were born.

function onDone() {
	console.log("hi there");
}

setTimeout(onDone, 5000);
console.log("after setTimeout");

--OUTPUT--
// after setTimeout
// hi there

<aside> 💡 How does this work? Why did we get an output like that?

Everything is mentioned in detail in this page → 1.5 Async, Await, and Promises

</aside>

Common asynchronous functions given by JS out of the box →

  1. reading a file fs.readFile
  2. sending a network request axios.get
  3. a deliberate timeout setTimeout, setInterval