Heap and stack
- Node.js course
- Expert
- Lesson 19/47
- 5 min
Learn Node.js heap and stack management.
Heap and stack
Node.js splits memory into two regions: the stack and the heap. The stack holds primitive values and function call frames; it is fast and cleaned automatically. The heap holds objects and arrays; it is managed by the garbage collector.
A classifyAllocation(type) function models this split: it returns 'stack' for 'primitive', otherwise 'heap'. Example: classifyAllocation('primitive') returns 'stack', classifyAllocation('object') returns 'heap'. The stack works LIFO (last in, first out); when a function returns its frame is removed immediately. Objects on the heap live until no reference remains; then the garbage collector reclaims them. This split is fundamental to understanding memory leaks.
Stack behavior
The stack grows and shrinks with function calls. When a function is called its frame (parameters, local variables) is pushed onto the stack; when it returns the frame is popped. This is automatic and fast; no garbage collection needed.
Example: when function add(a, b) { return a + b; } is called, a, b and the return address go on the stack. When the function ends they are removed. classifyAllocation('primitive') returns 'stack' because primitive values (number, string, boolean) live on the stack. classifyAllocation('object') returns 'heap' because objects live on the heap. This split determines which values enter garbage collection. Stack cleanup is instant; heap cleanup may be delayed.
Practice Write the region classifier
Write function classifyAllocation(type). Return type === 'primitive' ? 'stack' : 'heap'. Print console.log(classifyAllocation('primitive')) and console.log(classifyAllocation('object')).
Starter code
// Write a classifyAllocation function
// Return stack for primitives, heap otherwise
// Print two calls
// write hereSample solution
function classifyAllocation(type) {
return type === 'primitive' ? 'stack' : 'heap';
}
console.log(classifyAllocation('primitive'));
console.log(classifyAllocation('object'));Expected output
stack heap
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Where is an object stored?
- Stack
- Heap Correct answer
- Yok
- Her ikisi
Explanation: Objects live on the heap, managed by the garbage collector.
2 Return the stack value
return type === 'primitive' ? '____' : 'heap';
return type === 'primitive' ? 'stack' : 'heap';
Explanation: Primitives are stored on the stack.
3 Match each concept to its description
| Term | Meaning |
|---|---|
Stack |
Primitives and frames |
Heap |
Objects and arrays |
LIFO |
Last in, first out |
Garbage collector |
Cleans the heap |