- Courses
- 💻Programming Languages
- 🌐JavaScript
- Advanced Engine Concepts
- Memory Management
On this page
Memory Management: The Call Stack and Memory Heap
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
JavaScript is a high-level language that handles memory management automatically through a process called Garbage Collection. However, for an engineer to write performant, industrial-grade code, it is necessary to understand how the engine allocates physical hardware resources. Memory management in JavaScript is divided into two primary structures: the Call Stack and the Memory Heap.
The Call Stack: Static Memory Allocation
The Call Stack is a high-speed memory structure that operates on the LIFO (Last In, First Out) principle. Its primary responsibility is to keep track of function execution and store primitive values.
- Primitive Storage: Data types like
Number,String,Boolean,null, andundefinedare stored directly on the stack because their size is fixed and known at compile time. - Execution Contexts: Every time a function is invoked, a new frame is pushed onto the stack. This frame contains the function's local variables and its place in the execution flow.
- Automatic Cleanup: When a function finishes its execution, its frame is "popped" off the stack, and the memory for its local primitives is instantly reclaimed.
The Memory Heap: Dynamic Memory Allocation
Unlike the stack, the Memory Heap is a large, mostly unstructured region of memory. It is used for Dynamic Allocation, where the size of the data may change over time or is not known upfront.
- Reference Types: Objects, Arrays, and Functions are stored in the Memory Heap.
- Pointer Mechanism: While the actual object resides in the heap, a pointer (the memory address of that object) is stored on the Call Stack. When you access an object, the engine uses the pointer on the stack to find the data in the heap.
- Non-Linear Access: Because the heap is unstructured, the engine must work harder to find and manage this memory, making it slightly slower than the stack but far more flexible.
The Garbage Collection Process
JavaScript utilizes an automatic Garbage Collector (GC) to free up memory that is no longer being used. The goal of the GC is to identify "unreachable" memory—data that the program can no longer access.
The Mark-and-Sweep Algorithm
Modern engines, such as V8, primarily use the Mark-and-Sweep algorithm. The process follows these stages:
- Marking: The GC starts at the "roots" (the global object and the current call stack) and traverses all references. Every object it can reach is "marked" as active.
- Sweeping: The GC then scans the Memory Heap. Any object that was not marked during the first phase is considered unreachable.
- Reclaiming: The memory occupied by these unmarked objects is released back to the system.
Common Memory Leaks
Even with automatic garbage collection, developers can inadvertently create Memory Leaks by keeping references to data that is no longer needed, preventing the GC from "sweeping" it.
Global Variables
Variables attached to the window or global object are never garbage collected as long as the application is running. Accidental globals (variables declared without let, const, or var) are a frequent source of leaks.
Forgotten Timers and Callbacks
If a setInterval is started and never cleared using clearInterval, any variables referenced inside that interval's closure will remain in memory forever, even if the rest of the application no longer needs them.
Detached DOM Nodes
If you store a reference to a DOM element in a JavaScript variable and then remove that element from the page using remove(), the memory for that element cannot be reclaimed because the JavaScript variable still "points" to it.
// A potential leak: storing a reference to a deleted element
let btn = document.getElementById("submit-btn");
document.body.removeChild(btn);
// 'btn' still exists in the Memory Heap because the variable holds a reference.
// To fix this:
btn = null;
Hardware Efficiency Standards
To ensure your applications remain fast and responsive, observe these memory-safety rules:
- Nullify References: If you are finished with a large object or array, set its variable to
null. This breaks the reference and allows the Garbage Collector to reclaim the heap space. - Use Local Scope: Favor local variables over global ones. Local variables are cleared automatically when the function finishes, whereas globals persist.
- Clear Subscriptions: Always remove event listeners and clear intervals when a component or page is destroyed.
- Monitor Heap Snapshots: Use the "Memory" tab in Browser Developer Tools to take heap snapshots. If you see the "Total Heap Size" steadily increasing without ever dropping, your application has a memory leak.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Closures
Next
Currying & Composition
-
The Call Stack: Static Memory Allocation
-
The Memory Heap: Dynamic Memory Allocation
-
The Garbage Collection Process
- The Mark-and-Sweep Algorithm
-
Common Memory Leaks
- Global Variables
- Forgotten Timers and Callbacks
- Detached DOM Nodes
-
Hardware Efficiency Standards
