DEV Community

Esto Triramdani N
Esto Triramdani N

Posted on • Edited on

3

Callback in JavaScript

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
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

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
}
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!

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay