Giống nhiều ngôn ngữ khác, JavaScript có biến. Biến có thể coi như container (chứa) có tên. Đặt dữ liệu vào container và tham chiếu bằng tên.
Biến JavaScript được lưu trong bộ nhớ của tiến trình browser (browser process memory).
Các cách lưu trữ biến
- Memory (RAM): Biến khai báo trong code JS (
var,let,const) lưu trong heap/stack của JS engine (V8, SpiderMonkey...). Mất khi tab đóng hoặc reload. - Cookies: Lưu trên ổ cứng (hard disk) dưới dạng text file nhỏ. Gửi kèm mọi HTTP request đến domain. Dung lượng ~4KB/cookie. Dùng cho session, tracking.
- localStorage / sessionStorage (Web Storage): Lưu trên disk (localStorage persist, sessionStorage tab session). 5-10MB. Chỉ client-side, không gửi server tự động.
- IndexedDB: Database NoSQL trong browser, lưu lượng lớn, hỗ trợ index, transaction.
- Cache API / Service Worker: Cache network response, offline support.
Scope & Lifetime ảnh hưởng lưu trữ
- Global scope: Sống suốt đời trang (window/globalThis).
- Function/Block scope: Hủy khi function/block kết thúc (garbage collected).
- Closure: Biến bị "bắt giữ" bởi inner function → sống lâu hơn scope gốc.
Khi nào dùng cái gì?
| Storage | Dung lượng | Persistence | Use case |
|---|---|---|---|
| JS Variables | RAM (giới hạn bởi heap limit ~1-4GB) | Tab session | State runtime, computation |
| Cookies | 4KB | Expire date | Auth token, session ID (HttpOnly, Secure) |
| localStorage | 5-10MB | Vĩnh viễn (cho đến khi clear) | User preferences, cache data |
| sessionStorage | 5-10MB | Tab session | Form draft, temp state |
| IndexedDB | Nhiều (hundreds MB+) | Vĩnh viễn | Offline app, large dataset, search |