Table of contents
No headings in the article.
In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after some kind of event or operation has been completed. This allows the developer to write code that is executed at a later time, rather than in a blocking manner.
A callback function is a function that is "called back" at a later time after some operation has been completed. It is passed as an argument to another function, which is responsible for executing the callback when the operation is complete.
For example:
function add(a, b, callback) {
let result = a + b;
callback(result);
}
function printResult(result) {
console.log(`The result is: ${result}`);
}
add(1, 2, printResult);
In this example, the add
the function takes three arguments: two numbers to add and a callback function. The function adds the two numbers together and then calls the callback function, passing the result as an argument. The printResult
the function is defined as the callback function, which takes the result and logs it to the console.
Another example is using callbacks with event listeners, like the following:
let button = document.querySelector("button");
button.addEventListener("click", function() {
console.log("Button clicked!");
});
In this example, when the button is clicked, the callback function inside the addEventListener method will be called, and it logs "Button clicked!" to the console.
Callbacks are very useful in JavaScript, as they allow developers to create non-blocking code and handle events in an asynchronous way, which is particularly important in client-side web development.