Understanding Stack Memory
The Stack is a region of memory that stores temporary variables created by each function (including themain() function). It operates in a Last-In-First-Out (LIFO) manner, making it extremely fast and efficient for managing function execution contexts.
- Stores Primitive Types (numbers, booleans) directly.
- Memory is automatically allocated and deallocated as functions enter and exit.
- Fixed size, determined at the start of the program.
Example: Primitive Allocation
function main() {
let a = 10; // Stored directly on Stack
let b = 20; // Stored directly on Stack
let sum = a + b; // Calculated and stored on Stack
}Understanding Heap Memory
The Heap is a region for dynamic memory allocation. Unlike the stack, memory here is not managed automatically by CPU instructions but requires manual allocation (or garbage collection in languages like Java/JS/Python).
- Stores Objects and complex data structures.
- Accessed via References (pointers) stored on the Stack.
- Slower access than the Stack, but flexible in size.
Example: Reference Allocation
function main() {
// 'user' is a reference on the Stack
// pointing to the object { ... } on the Heap
let user = { id: 1, name: "Alice" };
// 'ref' is a copy of the ADDRESS,
// explaining why both point to the same object
let ref = user;
}Value Types vs. Reference Types
One of the most critical concepts in programming is understanding how data is passed. Value Types (primitives) copy the actual data when assigned to a new variable.Reference Types (objects) only copy the memory address (pointer). This visualizer helps demonstrate why modifying an object through one reference affects all other references to that same object.