Callback in JavaScript
Esto Triramdani N
Posted on November 14, 2022
Callback
I like to keep my definition of a callback straightforward: it’s simply a function passed as an argument to another function (or as an object property, if you’re using an object as a parameter). Down the line, that function will be called and executed within the code it was passed into. Let’s walk through an example to make it clear.
If you still don't get it, may this example could make you understand.
const multiply = ({ numb1, numb2 }) => {
return numb1 * numb2;
};
const sum = ({ numb1, numb2 }) => {
return numb1 + numb2;
};
const doWith2Numbers = ({ cb, numb1, numb2 }) => {
return cb({ numb1, numb2 });
}
doWith2Numbers({ cb: multiply, numb1: 2, numb2: 3 }) // 6
doWith2Numbers({ cb: sum, numb1: 2, numb2: 3 }) // 5
We have two functions that can multiply and sum of two numbers. So far, you might think, “We can just simply call that function like this.”
multiply({ numb1: 2, numb2: 3 })
sum({ numb1: 2, numb2: 3 })
This syntax works too, but it doesn’t give us a reusable blueprint. Here’s a simple case: I want to skip any action if numb2
is 2, 3, or 4
.
Rather than editing every function we’ve already created (like multiply
and sum
), we can just update doWith2Numbers
.
const doWith2Numbers = ({ cb, numb1, numb2 }) => {
const nothingNumbers = [2, 3, 4];
if (nothingNumbers.includes(num2)) return undefined;
// other code
}
Another example: we are creator of a package but we don’t really know what our package will do. We only know that function receives arguments. We will give the rest to other developer to describe the functionality. We will work with callback often when working with web framework, Express.js.
See you!
Posted on November 14, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.