Callback in JavaScript
A callback is a function that is passed as an argument to another function. The receiving function can then call that function when it needs to. In simple words, a callback allows us to say, "Here is a function; call it when you are ready."
What is a Callback?
JavaScript allows us to pass functions as values. This means a function can be stored in a variable, passed as an argument, or returned from another function. When we pass a function to another function and that function later calls it, the passed function is called a callback function.
function greet() {
console.log("Hello!")
}
function execute(callback) {
callback()
}
execute(greet)
Here, greet is passed to execute() as an argument. Inside execute(), the callback() parameter refers to the greet function, so calling callback() executes greet().
greet()
↓
passed to
↓
execute(greet)
↓
callback()
↓
greet() executes
Why Do We Need Callbacks?
Callbacks are useful when we want one function to perform some work and then execute another function at a particular point. They are especially important when working with asynchronous operations, where we may want something to happen after an operation finishes.
For example, setTimeout() accepts a callback:
setTimeout(function () {
console.log("2 seconds passed")
}, 2000)
Here, the function passed to setTimeout() is the callback. JavaScript calls this function after the timer finishes.
Passing a Function vs Calling a Function
When passing a callback, we usually pass the function without parentheses.
execute(greet)
This means:
"Pass the
greetfunction toexecute."
But:
execute(greet())
means:
"Call
greetnow and pass its returned value toexecute."
So these two are not the same.
Conclusion
A callback is simply a function passed to another function so that it can be called later or at a specific point in the execution. Understanding callbacks is important because they form the foundation for many JavaScript concepts, especially events, asynchronous programming, promises, and array methods.
Top comments (0)