JS quản lý bộ nhớ **tự động (automatic memory management)** qua Garbage Collector (GC). Không có cách explicit free memory như C/C++ (free(), delete).
Vòng đời bộ nhớ
- Allocate: Khởi tạo object → JS cấp phát memory.
- Use: Đọc/ghi property, method.
- Release: Khi variable **out of scope** hoặc không còn reference → GC thu hồi.
Ví dụ
function test() {
let x = { name: "John", age: 24 }; // allocate
console.log(x); // use
return null; // x out of scope → GC reclaim
}
test();
Ép GC (không khuyên dùng)
- Gán
nullcho variable global/long-lived:bigObj = null; - Dùng
WeakMap/WeakSet/WeakRefcho cache không cản GC.
Lưu ý: Không gọi GC thủ công được. Tin tưởng engine (V8, SpiderMonkey, JavaScriptCore) — chúng tối ưu rất tốt.