JavaScript Tutorial in Hindi #38 | Call Stack vs Callback Queue
1. Execution Context
- The environment where JavaScript code runs.
- It contains variables, functions, and the current scope.
- There are mainly two types:
- Global Execution Context: The default context, created when JS starts.
- Function Execution Context: Created whenever a function is invoked.
- Execution contexts are stacked in the Call Stack.
2. Call Stack
- A stack data structure that keeps track of function execution order.
- When a function is called, a new execution context is pushed onto the stack.
- When function finishes, its context is popped from the stack.
- JS runs synchronously, so it executes from the top of the stack down.
3. Asynchronous Tasks
- Tasks that happen outside the main thread, like:
setTimeout
, network requests, events.- These don’t block the call stack and run separately.
- When complete, their callback functions are queued for execution.
4. Callback Queue / Task Queue
- Holds the callbacks of asynchronous tasks ready to run.
- Functions wait here until the call stack is empty.
5. Event Loop
- Continuously checks if the call stack is empty.
- If empty, it takes the first callback from the callback queue and pushes it onto the call stack.
- 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
- Although the timeout is 0ms, its callback goes to the callback queue.
console.log('End')
runs before the callback because the call stack must be empty first.