André Casal
André Casal

Reputation: 1230

JavaScript: What is the data structure for the call stack?

I'm writing an article about JS concurrency model and event loop. I've read many (even internally) conflicting articles regarding the data structures of the call stack and Execution Contexts.

A JavaScript engine like Google's V8 is composed of two parts: the call stack and the heap. The stack is made up of Execution Contexts that hold information about the currently running function. When a function returns another function a closure is created around the returned function, i.e. the returned function now has memory associated with it.

For example:

function counterCreator() {
    let counter = 0
    return function count() {
        console.log(counter)
        return counter++
    }
}
const counter1 = counterCreator()
counter1() // 0
counter1() // 1
counter1() // 2

const counter2 = counterCreator()
counter2() // 0
counter2() // 1
counter2() // 2

When the code executes:

If the counterCreator() function returned a primitive data type (integer, float, undefined, null, etc), it would return that data type and be done. If the counterCreator() function returned a non-primitive data type (object or array), those non-primitive data types would be stored in the heap and it would return a pointer to their place in memory.

But what happens if the counterCreator() function returns another function? A closure with the variable counter needs to wrap around the returned function.

How is this closure stored in memory? What's the mechanism for the closured function to access it's closure variables? Is the call stack made up of Execution Contexts or merely pointers to Execution Contexts stored in the heap?

I've read several explanations:

Would appreciate thorough clarifications on this. The closest to the memory layout, the better.

Upvotes: 0

Views: 244

Answers (0)

Related Questions