JavaScript Tutorial in Hindi #38 | Call Stack vs Callback Queue

1. Execution Context

  1. The environment where JavaScript code runs.
  2. It contains variables, functions, and the current scope.
  3. There are mainly two types:
  4. Global Execution Context: The default context, created when JS starts.
  5. Function Execution Context: Created whenever a function is invoked.
  6. Execution contexts are stacked in the Call Stack.

2. Call Stack

  1. A stack data structure that keeps track of function execution order.
  2. When a function is called, a new execution context is pushed onto the stack.
  3. When function finishes, its context is popped from the stack.
  4. JS runs synchronously, so it executes from the top of the stack down.

3. Asynchronous Tasks

  1. Tasks that happen outside the main thread, like:
  2. setTimeout, network requests, events.
  3. These don’t block the call stack and run separately.
  4. When complete, their callback functions are queued for execution.

4. Callback Queue / Task Queue

  1. Holds the callbacks of asynchronous tasks ready to run.
  2. Functions wait here until the call stack is empty.

5. Event Loop

  1. Continuously checks if the call stack is empty.
  2. If empty, it takes the first callback from the callback queue and pushes it onto the call stack.
  3. This is how asynchronous callbacks get executed without blocking the main thread.

Visual Summary:

vbnet
CopyEdit
Call Stack: [Global Execution Context]
Event Loop: monitors call stack and callback queue
Callback Queue: holds async callbacks waiting to run

Example:

js
CopyEdit
console.log('Start');

setTimeout(() => {
console.log('Timeout callback');
}, 0);

console.log('End');

Output:

sql
CopyEdit
Start
End
Timeout callback
  1. Although the timeout is 0ms, its callback goes to the callback queue.
  2. console.log('End') runs before the callback because the call stack must be empty first.