JavaScript Call Stack

JavaScript Call Stack

JavaScript में Call Stack एक mechanism है जो functions के execution को manage करता है। Call stack यह track करता है कि कौन-सा function currently execute हो रहा है, और execution के बाद किस function को call किया जाना है। इसे एक stack की तरह imagine किया जा सकता है, जहां functions LIFO (Last In, First Out) order में execute होते हैं।

Call Stack कैसे काम करता है?

Call stack एक stack data structure की तरह काम करता है, जहां functions push होते हैं जब उन्हें call किया जाता है और pop होते हैं जब उनका execution पूरा हो जाता है। जब एक function execute होता है, तो उसे stack में सबसे ऊपर push किया जाता है। जैसे ही उसका execution पूरा होता है, वह stack से pop हो जाता है।

Example: Simple Call Stack Flow

function greet() {
    console.log("Hello!");
}

function sayName() {
    console.log("My name is John.");
    greet();  // Function inside a function
}

function start() {
    console.log("Starting...");
    sayName();  // Calling another function
}

start();

Call Stack Flow:

  • start() function call होता है, तो यह call stack में push होता है।
  • start() के अंदर sayName() function को call किया जाता है, इसलिए यह stack में push हो जाता है।
  • sayName() के अंदर greet() function को call किया जाता है, इसलिए इसे भी stack में push किया जाता है।
  • जब greet() का execution complete होता है, तो यह stack से pop हो जाता है, फिर sayName(), और आखिर में start() भी pop हो जाता है।

Stack Representation:

[ greet() ]   // Call greet() first
[ sayName() ]  // After greet() completes, return to sayName()
[ start() ]    // Finally, return to start()


Call Stack Real-Life Example (Simple Analogy)

Stack Overflow (Call Stack का Overflow)

No comments:

Post a Comment

Most recent Post

Promises in JavaScript

Promises in JavaScript Index What is a Promise? (Promise क्या है?) Syntax of a Promise (Promise का Syntax) Using a Promise...