DEV Community

Cover image for Callback functions (πŸ”–)
Aishanii
Aishanii

Posted on

2 1

Callback functions (πŸ”–)

When you call a function in another function, it is known as a callback function.

Easy example would be:

function hellojs(){
    console.log("Hi Javascript callback");
}

function call(hello){
    console.log("Hi user!")
    hello();
}

call(hellojs)
Enter fullscreen mode Exit fullscreen mode

Simply prints "Hi user!" and then "Hi Javascript callback". This is a synchronous callback.
As a developer, an API call with .then is generally where async callbacks come to play.

Why are they important though?

Web APIs like setTimeout() are used to time particular callback functions without blocking the main call stack. Like this, there is no function just idle and sitting in call stack and blocking it.

Another example if adding an event handler on any object, let's say an image here:

document.getElementById("random")
.addEventListener('mouseover', function(){
console.log("Hovered on image")
});
Enter fullscreen mode Exit fullscreen mode

Here the function is called when there is hovering on the image (random is the id given to the img tag). This function then appears on the call stack and is executed.

Web APIs, aynchronous Javascript, event listeners, there are a lot of keywords that have been mentioned here which will be discussed in the upcoming posts!

⭐Callback functions with event listeners yt video

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay