Interview question
What is the call stack in JavaScript and how does it relate to being single-threaded? JavaScript में call stack क्या है और single-threaded होने से इसका क्या रिश्ता है?
Answer
The call stack is a data structure that tracks function calls - each time a function is invoked, a frame is pushed on top; when it returns, the frame is popped off. JavaScript has exactly one call stack, meaning it can only execute one piece of code at a time.
function multiply(a, b) {
return a * b;
}
function square(n) {
return multiply(n, n); // multiply's frame pushed on top of square's
}
function printSquare(n) {
const result = square(n); // square's frame pushed on top
console.log(result);
}
printSquare(5);
// Call stack grows: printSquare -> square -> multiply
// Then unwinds as each function returns: multiply pops, square pops, printSquare pops
// A long-running synchronous function BLOCKS the entire stack
function blockingLoop() {
const start = Date.now();
while (Date.now() - start < 3000) {
// busy-wait for 3 seconds - nothing else can run, not even UI updates
}
}
console.log('Before');
blockingLoop(); // freezes the page for 3 seconds
console.log('After'); // only runs after blockingLoop fully completes
// Stack overflow - too many nested calls exceed the stack's size limit
function recurse() {
return recurse(); // no base case
}
// recurse(); // RangeError: Maximum call stack size exceeded
// This single-threaded, single-stack nature is WHY async operations
// (setTimeout, fetch, etc.) are handled OFF the call stack via Web APIs,
// only being pushed back onto the stack once they're ready to runCall stack एक data structure है जो function calls track करती है - हर बार function invoke होने पर एक frame ऊपर push होता है; return होने पर frame pop होता है। JavaScript का सिर्फ एक call stack है, यानी एक समय में सिर्फ एक code चल सकता है।
function multiply(a, b) {
return a * b;
}
function square(n) {
return multiply(n, n);
}
function printSquare(n) {
const result = square(n);
console.log(result);
}
printSquare(5);
// Stack बढ़ता है: printSquare -> square -> multiply
// फिर unwind होता है: multiply pop, square pop, printSquare pop
// लंबे समय तक चलने वाला synchronous function पूरे stack को BLOCK करता है
function blockingLoop() {
const start = Date.now();
while (Date.now() - start < 3000) {
// 3 सेकंड busy-wait - कुछ और नहीं चल सकता, UI भी freeze
}
}
console.log('Before');
blockingLoop(); // page 3 सेकंड freeze
console.log('After'); // blockingLoop पूरा होने के बाद ही चलता है
// Stack overflow - बहुत ज़्यादा nested calls
function recurse() {
return recurse(); // कोई base case नहीं
}
// recurse(); // RangeError: Maximum call stack size exceeded
// यही single-threaded nature है जिसकी वजह से async operations
// (setTimeout, fetch) Web APIs के ज़रिए stack से बाहर handle होते हैंWas this answer clear?