DEV Community

Kurapati Mahesh
Kurapati Mahesh

Posted on

 

What is callback in Javascript?

Callback: A function passed as an argument to other function is called callback function.

function calculation(a, b, fn) {
    return fn(a, b);
}

function add(a, b) {
    return a + b;
}

function mul(a, b) {
    return a * b;
}

function sub(a, b) {
    return a - b;
}

function div(a, b) {
    return a / b;
}

console.log(calculation(4, 2, mul));
Enter fullscreen mode Exit fullscreen mode

while passing function as argument to another function make sure to ignore appending parenthesis.

Thanks.

Contact: Twitter

Top comments (2)

Collapse
 
lukeshiru profile image
Luke Shiru

Just a heads up that you can add highlighting to the code blocks if you'd like. Just change:

code block with no colors example

... to specify the language:

code block with colors example

More details in our editor guide!

About the actual post, don't forget about arrow functions, that would make your code way easier to read:

const calculation = (a, b, fn) => fn(a, b);
const add = (a, b) => a + b;
const mul = (a, b) => a * b;
const sub = (a, b) => a - b;
const div = (a, b) => a / b;

console.log(calculation(4, 2, mul));
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
 
urstrulyvishwak profile image
Kurapati Mahesh

Purposefully, wrote functions instead of arrow functions. It will be more intuitive while reading.

Thank you for suggestion. Its colorful code now.

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await