Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 14, 2022 06:24 am GMT

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 }) // 6doWith2Numbers({ 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 })

It is also a valid syntax but we dont 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}

Another example: we are creator of a package but we dont 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!


Original Link: https://dev.to/estotriramdani/callback-in-javascript-3hp6

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To