Callbacks in JavaScript

Trying to better understand an abstract JavaScript concept.

I wanted to write this article about callback functions in JavaScript because honestly speaking, the concept is a bit hazy. I’ll being providing an example below to help clarify this concept.

What is a callback function?

A callback function is a function passed into another function as an argument. Since the argument is a function, when it gets called inside the outer function, it will get invoked and do some action.

Here is a simple example below of a callback function.

callback function

This callback is synchronous and called immediately. The code here is running from top to bottom. The message function is being passed into the userInput function as an argument. Also, when a function is used as an argument be sure to not include the parenthesis.

In my next blog, I’ll cover asynchronous callback function which is used more frequently. This can be seen with fetch calls, for example when using .then to see if a promise with get filled.

Full stack web developer