0
0
Javascriptprogramming~20 mins

Callbacks in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Callback Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Understanding callback execution order
What is the output of the following code?
Javascript
function first(cb) {
  console.log('First');
  cb();
}

function second() {
  console.log('Second');
}

first(second);
console.log('Third');
AFirst\nSecond\nThird
BFirst\nThird\nSecond
CSecond\nFirst\nThird
DThird\nFirst\nSecond
Attempts:
2 left
💡 Hint
Remember that callbacks run inside the function when called.
Predict Output
intermediate
2:00remaining
Callback with asynchronous behavior
What will be printed to the console when this code runs?
Javascript
function asyncOperation(cb) {
  setTimeout(() => {
    cb('Done');
  }, 100);
}

asyncOperation((message) => {
  console.log(message);
});
console.log('Start');
ADone
BDone\nStart
CStart
DStart\nDone
Attempts:
2 left
💡 Hint
setTimeout delays the callback, so the last console.log runs first.
Predict Output
advanced
2:00remaining
Callback with error handling
What is the output of this code?
Javascript
function fetchData(callback) {
  const error = null;
  const data = { id: 1, name: 'Test' };
  callback(error, data);
}

fetchData((err, result) => {
  if (err) {
    console.log('Error:', err);
  } else {
    console.log('Data:', result.name);
  }
});
AData: Test
BError: null
CData: undefined
DError: undefined
Attempts:
2 left
💡 Hint
Check how the callback handles the error and data parameters.
Predict Output
advanced
2:00remaining
Callback with multiple asynchronous calls
What will be the output of this code?
Javascript
function task1(cb) {
  setTimeout(() => {
    console.log('Task 1 done');
    cb();
  }, 200);
}

function task2() {
  console.log('Task 2 done');
}

task1(task2);
console.log('Start tasks');
ATask 2 done\nStart tasks\nTask 1 done
BStart tasks\nTask 1 done\nTask 2 done
CTask 1 done\nTask 2 done\nStart tasks
DStart tasks\nTask 2 done\nTask 1 done
Attempts:
2 left
💡 Hint
Remember setTimeout delays the callback, so synchronous logs run first.
Predict Output
expert
2:00remaining
Nested callbacks and variable scope
What is the output of this code?
Javascript
function outer(cb) {
  let count = 0;
  function inner() {
    count++;
    cb(count);
  }
  inner();
  inner();
}

outer((num) => {
  console.log('Count:', num);
});
ACount: undefined
BCount: 2
CCount: 1\nCount: 2
DCount: 1
Attempts:
2 left
💡 Hint
Check how many times the callback is called and what it logs each time.