During my journey of learning JavaScript and a few days in with React, I had to come to terms with callback functions. It was impossible to avoid its existence and blindly using it without understanding. To understand callback function we have to know a bit about functions. Here I want to talk about function expression, arrow function, and callback function.


What is a Callback function?

According to MDN doc:

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

In JavaScript, functions are objects, which means, like any other objects it can be assigned to a variable and passed as an argument to another function. In a nutshell, a callback function is a function that is provided as a parameter for other methods such as forEach method or addEventListener method and gets invoked at a certain point in time.

Passing functions as arguments

So how do we do this? Let’s see with an example below:

document.addEventListener(‘click’,whoAmI);

//whoAmI Function Declaration(Function Statement)
function whoAmI(event){
  console.log(event.target.tagName)
}

We attached the ‘click’ event listener to document with whoAmI function as a parameter that logs the tag name of the clicked target. Whenever ‘click’ happens whoAmI function will be called with an _event_ argument. We call whoAmI a callback function.

When we call a function by its name followed by ( ), we are telling the function to execute its code. When we name a function or pass a function without the ( ), the function does not execute.** The callback function doesn’t execute right away. Instead, the addEventListener method executes the function when the event occurs.**

One more thing I want to mention is because we used function declaration, we were able to call thewhoAmI function before it was declared. It’s the magic of hoisting in JS. But with function expression, it doesn’t get hoisted. So the order of writing function expressions and using them as callback would be crucial.

#callback #javascript #callback-function #function #javascript-fundamental

Intro to Callback in JavaScript
4.50 GEEK