JavaScript Callback Function Explained for Beginners
May 1, 2022
5 views
Loading...
Today I will tell you about JavaScript callback functions with the help of examples.
Callback function is a block of code that performs a certain task when called. For example,
// function
function sum(a, b) {
return a + b
}
sum(5, 6)
In the above code, a value is provided as an argument to the sum() function. In JavaScript, you can pass function as an argument to a another function. This function passed as an argument inside of another function is called a callback function. For example,
//function
function calc(a, b, func) {
console.log(`${a} , ${b}`)
return func(a, b)
}
// callback function
function sum(a, b) {
return a + b
}
// passing function as an argument
calc(4, 5, sum)
// output will be
// 4 , 5
// 9
Here while calling the calc() function, three arguments are passed. The sum() function is a callback function.
Hope, this post will help you to understand the basic of Javascript Callbacks. Please Share If you like this post.