What is a callback?
callback
is always a function that is being passed into another function.let foobar = function (callback) {
console.log("foo");
callback();
console.log("bar");
};
let sayHello = function () {
console.log("hello");
};
foobar(sayHello); // prints
// foo
// hello
// bar
let foobar = function (callback) {
console.log("foo");
callback();
console.log("bar");
};
foobar(function () {
console.log("hello");
}); // prints
// foo
// hello
// bar
Anonymous Callback
: When we use a function expression directly.A More Interesting Example
let add = function (num1, num2, cb) {
let sum = num1 + num2;
let result = cb(sum);
return result;
};
let double = function (num) {
return num * 2;
};
console.log(add(2, 3, double)); // 10
let add = function (num1, num2, cb) {
let sum = num1 + num2;
let result = cb(sum);
return result;
};
console.log(add(60, 4, Math.sqrt)); // 8
Math.sqrt
built in function being passed directly in as an argument.Refactoring for an Optional Callback
let add = function (num1, num2, cb) {
if (cb === undefined) {
return num1 + num2;
} else {
return cb(num1 + num2);
}
};
console.log(add(9, 40)); // 49
console.log(add(9, 40, Math.sqrt)); // 7
First-Class Object
: A type that supports the same basic operations as most other types. (i.e. Numbers, Strings & Booleans)First-Class Objects must be able to do three things:
They can be returned in functions.
Higher-Order Function
: A function that should either accept another function as an argument, or return a function as an output.Callback Functions are passed into Higher-Order Functions.
Interesting Interaction.
let foo = function () {
let bar = function () {
console.log("interesting");
};
return bar;
};
console.log(foo()); // [function: bar]
let res = foo();
console.log(rest); // interesting.