Callback
Callback = the primitive mechanism: you pass a function f to another function so f is called back later when the result is ready; control flow is still single-threaded but you must manually nest/chain these handlers (“callback hell”).
In JavaScript, a function is a special kind of object/ data type which you can pass as an argument. This is one of the most useful features of JavaScript programming language. When you call a function and you do not know when that function will return required result. Here you can pass a callback, which can be call when the result will come.
- Any function that is passed as an argument is called a callback function.
- In JavaScript, functions are objects. So functions can take functions as arguments, and can be returned by other functions. These functions are called higher-order functions.
- Callbacks are a way to make sure certain code doesn’t execute until other code has already finished execution.
var ifElse = function(condition, isTrue, isFalse) {
if (condition) {
return isTrue();
}
else {
return isFalse();
}
};
ifElse(true, function() {
console.log(true);
}, function() {
console.log(false);
})