Callbacks
Callbacks in JavaScript are functions that are passed as arguments to other functions.
Callbacks in JavaScript are functions that are passed as arguments to other functions. This is a very important feature of asynchronous programming, and it enables the function that receives the callback to call our code when it finishes a long task, while allowing us to continue the execution of the code.
For example:
let callback = function() {
console.log("Done!");
}
setTimeout(callback, 5000);This code waits 5 seconds and prints out “Done!” when the 5 seconds are up. Note that this code will not work in the interpreter because it is not designed for handling callbacks.
It is also possible to define callbacks as anonymous functions, like so:
setTimeout(function() {
console.log("Done!");
}, 5000);Like regular functions, callbacks can receive arguments and be executed more than once.
Try it
Expected output
1
2
3Solution
function useCallback(callback)
{
callback(1);
callback(2);
callback(3);
}
function callback(sentence)
{
// TODO: print out sentence
console.log(sentence);
}
// TODO: execute useCallback with the callback as the argument
useCallback(callback);Get the JavaScript agent pack
A battle-tested AGENTS.md, the review checklist, and the failure-mode cheat sheet for JavaScript. One email, then occasional updates when the tooling shifts. No course pitch.
AGENTS.md now — no email needed.