JavaScript Memory Management
Learn about memory allocation and garbage collection in JavaScript.
1. Memory Allocation
JavaScript automatically allocates memory when you create variables.
JavaScript Code
Live JavaScript representation with highlighted changes
// Memory is allocated for these variablesconst n = 123;const s = "string";const o = { a: 1 };
2. Garbage Collection
JavaScript frees memory automatically when it's no longer needed. The main algorithm is Mark-and-sweep.
JavaScript Code
Live JavaScript representation with highlighted changes
let x = { a: { b: 2 } }; // 2 objects createdlet y = x; // y references the same objectx = 1; // Now the original object is only referenced by y// When y goes out of scope, the object can be garbage collected.
3. Circular References
Older reference-counting garbage collectors had issues with circular references, but modern mark-and-sweep algorithms can handle them.
JavaScript Code
Live JavaScript representation with highlighted changes
function createCircularReference() {let obj1 = {};let obj2 = {};obj1.a = obj2;obj2.a = obj1;// Modern garbage collectors can handle this!}createCircularReference();
Simulation Output