Search code examples
javascriptmemoryv8

In JavaScript loops, how are block-level allocations managed in memory?


I am curious about the way JavaScript interpreters manage block-level variables like let and const.

Say I have a loop:

for (let i = 0; i < 100; i++) {
  const square = i * i;
}

Where exactly are i and square being allocated?

I understand that there is a frame stack; that each function call adds a new dictionary-like object representing the function's lexical context. When a function exits, we decrement a stack pointer. This means that we can run functions with variables without creating garbage on the heap.

But where are our block variables? Do we augment the frame stack with another item? Are they 'flattened' onto the context but with a special flag or symbol to differentiate them from variables in sibling blocks?

Finally, where can I generally learn how JavaScript interpreters (like V8) manage memory?


Solution

  • Here are some great stack overflow answers that might help you.
    Memory allocation for JavaScript types
    How variables are allocated memory in Javascript?
    JavaScript variables declare outside or inside loop?
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management
    And of course the documentation of V8.
    I hope reading these will help you understand more about javascript memory management.