MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Callbacks0%
Study Materials
JavaScript for IntermediateProgress 0%
1.1Block Scope with let & const1.2Template Literals1.3Destructuring Arrays and Objects1.4Default Parameters1.5Enhanced Object Literals
7.1Callbacks7.2Promises Basics7.3Promise Chaining7.4Intro to Async/Await
HomeTutorialsJavaScript for IntermediateCallbacks
Promises Basics

Callbacks

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

JavaScript is a single-threaded runtime environment driven by a non-blocking Event Loop. In order to perform long-running tasks (such as network requests, timer delays, or file I/O) without freezing the user interface, JavaScript relies on asynchronous callbacks.


1. What is a Callback Function?

A callback is simply a function passed into another function as an argument, intended to be executed ("called back") at a designated time or after an asynchronous operation completes.

Synchronous vs. Asynchronous Callbacks

1// 1. Synchronous Callback: Executes immediately during caller execution
2const numbers = [1, 2, 3];
3numbers.forEach((num) => console.log(`Sync: ${num}`));
4 
5// 2. Asynchronous Callback: Defers execution until an event completes
6console.log('Task A: Start timer');
7setTimeout(() => {
8 console.log('Task B: Timer callback executed after 1000ms');
9}, 1000);
10console.log('Task C: Script continues uninterrupted');

Execution Output Order:

  1. 1
    Task A: Start timer
  2. 2
    Task C: Script continues uninterrupted
  3. 3
    Task B: Timer callback executed after 1000ms

2. The JavaScript Event Loop & Callback Queue

How does JavaScript manage asynchronous callbacks with only a single thread?

1┌──────────────────────────────────────────────────────────┐
2│ CALL STACK (Single Thread) │
3│ console.log('A') ──► setTimeout(...) ──► console.log('C')│
4└─────────────────────────────┬────────────────────────────┘
5 │ Registers Web API Timer
6 ▼
7┌──────────────────────────────────────────────────────────┐
8│ WEB APIs (Browser Background Engine) │
9│ Timer countdown (1000ms) │
10└─────────────────────────────┬────────────────────────────┘
11 │ Timer expires
12 ▼
13┌──────────────────────────────────────────────────────────┐
14│ CALLBACK / TASK QUEUE (FIFO) │
15│ [ () => console.log('B') ] │
16└─────────────────────────────┬────────────────────────────┘
17 │ Event Loop pushes when Call Stack is empty!
18 ▼
19 [ Executes Callback ]
  1. 1
    Functions execute on the Call Stack.
  2. 2
    Asynchronous operations (setTimeout, fetch) are delegated to browser Web APIs.
  3. 3
    Upon completion, the callback is placed into the Callback Queue (Task Queue).
  4. 4
    The Event Loop constantly monitors the Call Stack. When the Call Stack is empty, it pushes the queued callback onto the stack.

3. The Classic Problem: "Callback Hell" (Pyramid of Doom)

When multiple dependent asynchronous operations must execute sequentially, nesting callbacks leads to unmaintainable, deeply indented code:

1// ANTI-PATTERN: Callback Hell
2getUser(userId, (err, user) => {
3 if (err) return handleError(err);
4 getOrders(user.id, (err, orders) => {
5 if (err) return handleError(err);
6 getOrderDetails(orders[0].id, (err, details) => {
7 if (err) return handleError(err);
8 processPayment(details.amount, (err, receipt) => {
9 if (err) return handleError(err);
10 console.log('Transaction finalized:', receipt);
11 });
12 });
13 });
14});

Pitfalls of Callback Hell:

  • Deeply nested indentation ("Pyramid of Doom").
  • Repetitive, scattered error handling in every callback.
  • High cognitive load and severe difficulty tracking control flow.
  • Lack of native return values or composite operations.

4. Modern Solution: Evolution to Promises

To solve Callback Hell, ES6 introduced Promises, which flatten nested callbacks into linear chains (.then().catch()), later elevated by ES2017 async/await.


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is a callback function in JavaScript?
Question 2
What is the primary role of the JavaScript Event Loop?
Question 3
What is "Callback Hell"?
Question 4
In what order will console.log('1'), setTimeout(() => console.log('2'), 0), and console.log('3') print?
Question 5
What standard Node.js convention was historically used for callback arguments?
Next Lesson

Promises Basics

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Object Destructuring in DepthPromises Basics

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext