Challenge - 5 Problems
Callback Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of asynchronous callback with loop variable
What will be the output of this code snippet?
Javascript
for (var i = 0; i < 3; i++) { setTimeout(function() { console.log(i); }, 100); }
Attempts:
2 left
💡 Hint
Think about how the variable i is shared in the loop and when the callbacks run.
✗ Incorrect
The variable i is declared with var, which has function scope. By the time the callbacks run, the loop has finished and i is 3. So all callbacks print 3.
❓ Predict Output
intermediate2:00remaining
Fixing callback loop with let
What will be the output of this code snippet?
Javascript
for (let i = 0; i < 3; i++) { setTimeout(function() { console.log(i); }, 100); }
Attempts:
2 left
💡 Hint
Consider the scope of
let inside the loop.✗ Incorrect
Using let creates a new binding for each loop iteration. Each callback closes over its own i, so the output is 0, 1, 2.
❓ Predict Output
advanced2:30remaining
Callback with multiple asynchronous calls and variable capture
What will be the output of this code?
Javascript
function fetchData(id, callback) { setTimeout(() => { callback('Data for ' + id); }, 100); } for (var i = 1; i <= 3; i++) { fetchData(i, function(data) { console.log('Received:', data); }); }
Attempts:
2 left
💡 Hint
Check how the argument
id is passed to the callback.✗ Incorrect
The id is passed as an argument to fetchData and used inside the callback. Each call has its own id, so the output matches 1, 2, 3.
❓ Predict Output
advanced2:00remaining
Callback error handling with missing callback
What will happen when this code runs?
Javascript
function doWork(callback) { setTimeout(() => { if (callback) { callback(null, 'Success'); } }, 100); } doWork();
Attempts:
2 left
💡 Hint
Check if the callback is called only when it exists.
✗ Incorrect
The function checks if callback exists before calling it. Since doWork is called without arguments, no callback is called and no error occurs.
❓ Predict Output
expert2:30remaining
Nested callbacks and variable shadowing
What will be the output of this code?
Javascript
var x = 1; function outer(callback) { var x = 2; callback(); } outer(function() { console.log(x); });
Attempts:
2 left
💡 Hint
Consider the scope where the callback is defined and where it is called.
✗ Incorrect
The callback is defined in the global scope where x is 1. Inside outer, x is 2 but the callback does not close over that variable. So it prints 1.