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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more