Callbacks in JavaScript
Samarth Goudar

Samarth Goudar @10samarth

About: I’m a software engineer passionate about creating exceptional software and having some fun along the way.

Location:
Los Angeles
Joined:
May 7, 2025

Callbacks in JavaScript

Publish Date: May 15
0 0

What is a Callback?

A callback is a function passed into another function, to be called later when something happens or a task is finished.

Analogy:

Imagine you order food and give the restaurant your phone number so they can call you when your food is ready. Your phone number is the callback.

Why Are Callbacks Important?

JavaScript is single-threaded and often needs to wait for things (like loading data or waiting for a user action).

Instead of stopping everything, it uses callbacks to say, “Do this later, when the waiting is done.”

How Do Callbacks Work?

1. Writing a Function That Accepts a Callback

function doSomethingLater(callback) {  
console.log("Doing something...");  
callback();  
}  
Enter fullscreen mode Exit fullscreen mode

2. Defining the Callback Function

function sayHello() {  
console.log("Hello, I'm the callback!");  
}  
Enter fullscreen mode Exit fullscreen mode

3. Passing the Callback

doSomethingLater(sayHello);  
Enter fullscreen mode Exit fullscreen mode

Output:

Doing something...  
Hello, I'm the callback!  
Enter fullscreen mode Exit fullscreen mode

4. Using Inline (Anonymous) Callbacks

doSomethingLater(function() {  
console.log("This is an inline callback!");  
});  
Enter fullscreen mode Exit fullscreen mode

Real-Life Applications

setTimeout and setInterval

setTimeout(function() {  
console.log("This runs after 2 seconds");  
}, 2000);  
Enter fullscreen mode Exit fullscreen mode

Event Listeners

button.addEventListener('click', function() {  
console.log("Button clicked!");  
});  
Enter fullscreen mode Exit fullscreen mode

Fetching Data (with Promises, but still uses callbacks)

fetch('https://api.example.com/data')  
.then(function(response) {  
return response.json();  
})  
.then(function(data) {  
console.log(data);  
});  
Enter fullscreen mode Exit fullscreen mode

Common Misconceptions

  • Callbacks are not always asynchronous.

    Some callbacks are called right away.

  • Callbacks are just functions.

    There’s nothing special about them except how they’re used.

Callback Cheat Sheet

Definition:

A callback is a function you pass to another function to be called later.

Basic Example:

function callback() { ... }  
someFunction(callback);  
Enter fullscreen mode Exit fullscreen mode

Anonymous Example:

someFunction(function() { ... });  
Enter fullscreen mode Exit fullscreen mode

Typical Uses:

  • setTimeout, setInterval

  • Event handling (like clicks)

  • Fetching data from APIs

Key Point:

Callbacks help JavaScript handle tasks that take time, so your code can keep running without waiting.

Comments 0 total

    Add comment