DEV Community

Hiral
Hiral

Posted on

Callbacks in JavaScript: Why They Exist

Functions as Values in JavaScript
Before callbacks make sense, you need to accept one slightly mind-bending idea: in JavaScript, a function is just a value — exactly like a number or a string. You can store it in a variable, pass it to another function, or return it from one.

const greet = function(name) {
  console.log("Hello, " + name);
};

// We can pass it around like any value
const myFunc = greet;
myFunc("Alice")
Enter fullscreen mode Exit fullscreen mode

What is a Callback Function?
A callback function is simply a function that is passed into another function and then executed later.

function greetUser(name, callback) { 
console.log("Hi " + name); 
callback(); 
} 
function sayBye() { 
console.log("Goodbye!"); 
} 
greetUser("Alice", sayBye);
Enter fullscreen mode Exit fullscreen mode

Output:
Hi Alice
Goodbye!
Here, sayBye is the callback function.

Passing Functions as Arguments

Callbacks work because functions can be passed just like any other value

Example:

function processNumber(num, operation) {
  return operation(num);
}

function double(x) {
  return x * 2;
}

console.log(processNumber(5, double)); // Output: 10

You can also use anonymous functions:

processNumber(5, function(x) {
  return x + 3;
});

Or arrow functions:


processNumber(5, x => x - 1);
Enter fullscreen mode Exit fullscreen mode

Why Callbacks Are Used (Especially in Asynchronous Programming)

JavaScript often deals with tasks that take time:

  • Fetching data from an API
  • Reading files
  • Waiting for user input

Instead of blocking the program, JavaScript uses callbacks to handle these tasks after they finish.
Example with setTimeout:

console.log("Start");

setTimeout(function() {
  console.log("This runs later");
}, 2000);

console.log("End");

Enter fullscreen mode Exit fullscreen mode

Output:
Start
End
This runs later

The callback runs after 2 seconds, without stopping the rest of the code.

Top comments (0)