Chapter XIV · Heap & Memory
Memory
JavaScript memory management revolves around allocating space when variables are created and releasing it when no longer needed.
01 How It Works
Think of renting a storage locker, using it for inventory, and cleaning it out when items are discarded.
JavaScript engines handle memory lifecycles automatically through allocation, usage, and garbage collection.
example.js
let username = "JavaScript"; // Memory allocated
// ... code execution ...
username = null; // Memory eligible for reclamation
1. Allocate memory required for variables, objects, and functions.
2. Use allocated memory during program execution.
3. Release unneeded memory via garbage collection.
02 Practical Example
Here is how you might see this concept applied in real-world code:
practical.js
function createData() {
let heavyArray = new Array(1000000).fill(0);
return heavyArray.length;
}
createData(); // Array memory becomes eligible for cleanup after scope exit.
Key Takeaway
JavaScript automates memory management, though developers must avoid memory leaks from unreferenced retained pointers.