Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Biến JavaScript được lưu trữ ở đâu?


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ì?

StorageDung lượngPersistenceUse case
JS VariablesRAM (giới hạn bởi heap limit ~1-4GB)Tab sessionState runtime, computation
Cookies4KBExpire dateAuth token, session ID (HttpOnly, Secure)
localStorage5-10MBVĩnh viễn (cho đến khi clear)User preferences, cache data
sessionStorage5-10MBTab sessionForm draft, temp state
IndexedDBNhiều (hundreds MB+)Vĩnh viễnOffline app, large dataset, search