In JavaScript, stack and heap memory are two areas where the language manages memory for variables and data during the execution of a program. Understanding these concepts helps clarify how JavaScript handles data storage, memory allocation, and garbage collection.
Stack Memory:
- Definition: A stack is a memory structure used to store primitive values and the execution context of function calls (e.g., local variables, function arguments).
- Structure: Works on a LIFO (Last In, First Out) basis. The last item added is the first to be removed.
- Usage:
- Stores primitive data types:
undefined
, null
, boolean
, number
, bigint
, string
, and symbol
.
- Holds references to objects stored in the heap.
Key Characteristics:
- Fast access: Memory allocation and deallocation in the stack are quick because of its linear structure.
- Limited size: Stack memory is typically smaller and limited compared to heap memory.
- Temporary storage: Data is cleared when the function execution is complete or the variable goes out of scope.
Example:
function add(a, b) {
let sum = a + b; // `a`, `b`, and `sum` are stored in the stack.
return sum;
}
add(3, 4);
Heap Memory:
- Definition: The heap is a larger memory area used for storing objects and reference types.
- Structure: Unlike the stack, it is not ordered and allows dynamic memory allocation.
- Usage:
- Stores reference data types, such as objects, arrays, and functions.
Key Characteristics:
- Dynamic allocation: Memory is allocated and managed dynamically as needed during runtime.
- Garbage collection: The JavaScript engine (e.g., V8 in Chrome) automatically clears unused objects in the heap via garbage collection.