DEV Community

Esto Triramdani N
Esto Triramdani N

Posted on

Callback in JavaScript

Callback

I usually make callback definition this simple: callback is a function that passed as a function argument (or object property if you using object as function paramter). Later, that function we passed will be executed inside it. Let's take an example.
I simplified callback definition for myself

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
Enter fullscreen mode Exit fullscreen mode

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 })
Enter fullscreen mode Exit fullscreen mode

It is also a valid syntax but we don’t have blueprints that can reusable later. This simple case: I want to do nothing if numb2 is 2, 3, or 4.

Instead of editing all functions we have created (multiply and sum). We can just edit doWith2Numbers.

const doWith2Numbers = ({ cb, numb1, numb2 }) => {
    const nothingNumbers = [2, 3, 4];
    if (nothingNumbers.includes(num2)) return undefined;
    // other code
}
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)