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

Coding Techniques

Callbacks · Study material

Flattening callback hell with named functions

Give every step a name and pass the next step as its callback. The flow reads top to bottom and each function handles its own errors:

// Flatten callback hell by giving each step a name and a single job
function step(name, value, cb) { setTimeout(() => cb(null, `${value} → ${name}`), 0); }

function validate(order) { step("validate", order, charge); }
function charge(err, order) { if (err) return fail(err); step("charge", order, ship); }
function ship(err, order) { if (err) return fail(err); step("ship", order, done); }
function done(err, order) { if (err) return fail(err); console.log(order); }
function fail(err) { console.log("Failed:", err.message); }

validate("order #7");

Output

order #7 → validate → charge → ship

try/catch cannot catch async errors

By the time an async callback throws, the surrounding try block has long finished. Catch errors inside the callback and pass them on through the error-first argument:

// try/catch only catches errors thrown while the try block is running.
// An async callback runs later, outside it – so report errors through the callback instead.
function loadSettings(cb) {
  setTimeout(() => {
    try {
      const data = JSON.parse("{ bad json }");
      cb(null, data);
    } catch (e) {
      cb(e);                                   // pass the error to the caller
    }
  }, 0);
}
try {
  loadSettings((err) => console.log(err ? `callback got ${err.name}` : "ok"));
  console.log("try block finished – nothing thrown yet");
} catch {
  console.log("never reached");
}

Output

try block finished – nothing thrown yet
callback got SyntaxError

Callbacks vs promises

CallbacksPromises
Sequencingnestingflat .then chains / await
Errorschecked in every callbackone .catch / try…catch
Called how many times?up to the caller (could be 0 or 2)settles exactly once
Running in parallelmanual countersPromise.all
Still the right tool forarray methods, events, streamsone-off asynchronous results

Callbacks checklist

  • Pass functions, not function calls.
  • Follow error-first for async callbacks and always return after handling an error.
  • Make an API always async (or always sync), never both.
  • Store parallel results by index.
  • Guard callbacks you hand to untrusted code (once, timeouts).
  • Convert repeated nesting to promises or async/await.

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