LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 19 of 25

Callbacks Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Callbacks · Study material

A callback is a function passed to another function, to be called by it – now (like the function you give to map) or later (when a timer fires, a file is read or a button is clicked). Callbacks were JavaScript's first tool for asynchronous code, and they still power array methods, event listeners, timers and many Node.js APIs. Interviews ask about the order in which callbacks run, the error-first convention, callback hell, inversion of control and how promises improve on callbacks. This topic covers all of that. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.

Synchronous callbacks

Many callbacks run immediately, while the function that received them is still running: the callbacks of forEach, map, filter, sort and of your own helpers. Code after the call runs only when all of them have finished.

// A callback is a function passed to another function, which decides when to call it
function repeat(times, callback) {
  for (let i = 1; i <= times; i++) callback(i);   // called right now, during repeat()
}
repeat(3, (n) => console.log(`step ${n}`));

// Array methods take synchronous callbacks too
const prices = [499, 99, 1499];
console.log(prices.filter((p) => p < 1000), [..."cba"].sort((a, b) => a.localeCompare(b)));

Output

step 1
step 2
step 3
[ 499, 99 ] [ 'a', 'b', 'c' ]

Asynchronous callbacks

Callbacks given to timers, network requests, file reads and event listeners run later, after the current code has finished and the engine is free – even setTimeout(fn, 0) waits. The Event Loop topic explains the exact order; here, remember: synchronous code first, then callbacks, timers in order of their delay.

console.log("1. order placed");
// An asynchronous callback runs LATER – after the current code has finished – even with a 0 ms delay
setTimeout(() => console.log("3. order confirmed (callback)"), 0);
console.log("2. showing receipt");

Output

1. order placed
2. showing receipt
3. order confirmed (callback)

Passing callbacks and their arguments

Pass the function itself (notify), not the result of calling it (notify()). To supply arguments, wrap the call in an arrow function, or use the extra parameters that setTimeout forwards to the callback.

function notify(user, channel) {
  console.log(`Notify ${user} via ${channel}`);
}
setTimeout(notify, 10, "Asha", "email");        // extra setTimeout arguments are passed to the callback
setTimeout(() => notify("Ravi", "sms"), 0);     // or wrap the call in an arrow function

Output

Notify Ravi via sms
Notify Asha via email

Error-first callbacks

Node.js APIs follow a convention: the callback's first parameter is an error (null on success) and the result comes after it. Always check the error first and return after handling it, so the success code does not run too.

// Node.js convention: callback(error, result) – error is null on success
function fetchUser(id, callback) {
  setTimeout(() => {
    if (id <= 0) callback(new Error("Invalid id"));
    else callback(null, { id, name: id === 1 ? "Asha" : "Ravi" });
  }, 0);
}
const handle = (err, user) => {
  if (err) return console.log("Error:", err.message);   // return: stop here on error
  console.log("User:", user.name);
};
fetchUser(1, handle);
fetchUser(-5, handle);

Output

User: Asha
Error: Invalid id

Callback hell

When each asynchronous step needs the previous step's result, callbacks nest inside callbacks, and the code becomes a rightward "pyramid of doom" that is hard to read, handle errors in and change. Named functions flatten it (see Coding Techniques); promises and async/await solve it properly.

function step(name, value, cb) {
  setTimeout(() => cb(null, `${value} → ${name}`), 0);
}
// Each step depends on the previous one, so the code drifts to the right: the "pyramid of doom"
step("validate", "order", (e1, a) => {
  step("charge", a, (e2, b) => {
    step("ship", b, (e3, c) => {
      console.log(c);
    });
  });
});

Output

order → validate → charge → ship

Inversion of control

Passing a callback means trusting the other code to call it correctly – exactly once, with the right arguments, at the right time. Buggy or malicious code may call it twice, never, too early or synchronously when you expected async. You can guard against some of this (e.g. with a once wrapper); promises solve it by design, because a promise settles only once.

// Passing a callback hands control to someone else's code. Protect yourself against misuse.
function onceOnly(cb) {
  let called = false;
  return (...args) => {
    if (called) return console.log("ignored extra call");
    called = true;
    cb(...args);
  };
}
function buggyPaymentLibrary(cb) {   // third-party code that calls back twice
  cb("paid");
  cb("paid");
}
buggyPaymentLibrary(onceOnly((status) => console.log("charge customer:", status)));

Output

charge customer: paid
ignored extra call

From callbacks to promises

A small adapter turns any error-first callback API into a function that returns a promise – Node.js ships one as util.promisify. Promises (next topic) and async/await (the topic after) are built on this idea.

function readConfig(name, cb) {
  setTimeout(() => (name ? cb(null, { name, debug: false }) : cb(new Error("No name given"))), 0);
}
// Wrap an error-first callback API in a Promise: the bridge to promises and async/await
const promisify = (fn) => (...args) =>
  new Promise((resolve, reject) => fn(...args, (err, data) => (err ? reject(err) : resolve(data))));

const readConfigAsync = promisify(readConfig);
readConfigAsync("app").then((c) => console.log("loaded", c.name));
readConfigAsync("").catch((e) => console.log("failed:", e.message));

Output

loaded app
failed: No name given

Common mistakes

  • Passing fn() instead of fn – you pass its return value, not the function.
  • Using an async result immediately – the callback has not run yet.
  • Forgetting return after the error branch – the callback runs twice.
  • Swapping the parameters – (data, err) instead of (err, data).
  • Wrapping async code in try/catch – errors thrown later in callbacks are not caught.
  • Calling the callback sometimes synchronously, sometimes asynchronously – unpredictable order.
  • Collecting parallel results with push – they arrive in finish order, not request order.

Key points to remember

  • A callback is a function passed to another function to be called by it.
  • Array-method callbacks are synchronous; timer and I/O callbacks are asynchronous.
  • Async callbacks run after the current code, even with a 0 ms delay.
  • Error-first: callback(err, result); check err and return.
  • Deep nesting = callback hell; flatten with named functions or use promises.
  • Callbacks give control to other code (inversion of control).
  • promisify turns callback APIs into promise APIs.

Frequently asked questions

Are callbacks outdated?

No. Synchronous callbacks (map, filter, sort) and event listeners are everywhere. For sequences of asynchronous steps, though, promises and async/await are clearer than nested callbacks.

Is every callback asynchronous?

No – being a callback says nothing about timing. forEach calls its callback immediately; setTimeout calls it later. Good APIs are consistent: always sync or always async.

Why does Node.js put the error first?

It makes error handling impossible to overlook: every callback must deal with the first argument before using the result.

Where can I learn more?

Read Higher-Order Functions, The Event Loop and Promises in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links