What is a callback in JavaScript?
map, setTimeout and addEventListener all take callbacks; the receiving function decides when to call them.
Callbacks · Exercise 1 of 4
Fifteen multiple-choice questions on JavaScript callbacks: synchronous and asynchronous callbacks, setTimeout, error-first callbacks, callback hell, inversion of control, this, consistent timing, async errors, parallel tasks and promisify. Pick an option to check your answer instantly.
What is a callback in JavaScript?
map, setTimeout and addEventListener all take callbacks; the receiving function decides when to call them.
Is the callback passed to arr.forEach synchronous or asynchronous?
Array-method callbacks run immediately. Being a callback says nothing about timing.
When does the callback in setTimeout(fn, 0) run?
Timer callbacks are queued and run only when the call stack is empty. 0 ms means "as soon as possible after that".
In Node.js-style callbacks, what is the first parameter?
callback(err, data): check err first, then use data.
What is "callback hell"?
Also called the pyramid of doom: each step nests inside the previous one's callback.
Which approach does not help with callback hell?
More inline nesting makes it worse. Named functions flatten the structure; promises and async/await remove the nesting.
What does "inversion of control" mean for callbacks?
A buggy library may call your callback twice or never. Promises reduce this risk because they settle exactly once.
Which line runs showAlert after 2 seconds?
showAlert() would run immediately and pass its return value. Strings are evaluated as code in browsers (and rejected by Node.js), and the order of arguments is callback, delay.
What does setTimeout(greet, 100, "Asha", "Hi") do?
Arguments after the delay are forwarded to the callback – an alternative to wrapping it in an arrow function.
Inside a method, why does setTimeout(function () { this.count++; }, 0) not update the object's count?
this in a regular function depends on the caller (the global object in browsers, a Timeout object in Node.js). An arrow keeps the method's this.
Timed online tests with instant scores and explanations.