0
0
Javascriptprogramming~20 mins

Callback pitfalls in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Callback Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
}
A0 1 2
B1 2 3
C0 0 0
D3 3 3
Attempts:
2 left
💡 Hint
Think about how the variable i is shared in the loop and when the callbacks run.
Predict Output
intermediate
2: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);
}
A0 1 2
B3 3 3
Cundefined undefined undefined
D0 0 0
Attempts:
2 left
💡 Hint
Consider the scope of let inside the loop.
Predict Output
advanced
2: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);
  });
}
A
Received: Data for undefined
Received: Data for undefined
Received: Data for undefined
B
Received: Data for 3
Received: Data for 3
Received: Data for 3
C
Received: Data for 1
Received: Data for 2
Received: Data for 3
D
Received: Data for 1
Received: Data for 1
Received: Data for 1
Attempts:
2 left
💡 Hint
Check how the argument id is passed to the callback.
Predict Output
advanced
2: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();
AThrows TypeError: callback is not a function
BNo output, no error
CPrints 'Success'
DThrows ReferenceError: callback is not defined
Attempts:
2 left
💡 Hint
Check if the callback is called only when it exists.
Predict Output
expert
2: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);
});
A1
BReferenceError
Cundefined
D2
Attempts:
2 left
💡 Hint
Consider the scope where the callback is defined and where it is called.