เหมือนภาษาโปรแกรมอื่นๆ JavaScript มีตัวแปร คิดเป็น ถังที่มีชื่อ (named containers) วางข้อมูลลงไป แล้วอ้างอิงได้โดยชื่อ
ตัวแปร JavaScript ถูกเก็บใน หน่วยความจำของกระบวนการเบราว์เซอร์ (browser process memory) วิธีการเก็บตัวแปร:
- ตัวแปรที่ประกาศในโค้ด JavaScript จะถูกเก็บในหน่วยความจำของ browser process
- Cookies ก็สามารถเก็บตัวแปรได้ มักถูกเก็บบนฮาร์ดดิสก์
ขยายความ: Storage Options ใน Browser
| Storage | ขนาด | อายุ | ส่งไป Server | ใช้สำหรับ |
|---|---|---|---|---|
| Variables (Memory) | ~MB | Session (reload = หาย) | ไม่ | Runtime data, state |
| localStorage | ~5-10MB | ถาวร (จนกว่าจะลบ) | ไม่ | Preferences, cache |
| sessionStorage | ~5-10MB | Tab session (ปิด tab = หาย) | ไม่ | Temp data per tab |
| Cookies | ~4KB | ตาม expires/max-age | ใช่ (ทุก request) | Auth, tracking |
| IndexedDB | ~hundreds MB | ถาวร | ไม่ | Large structured data |
| Cache API | Dynamic | ถาวร | ไม่ | Offline, network requests |
สรุป: ตัวแปร JS อยู่ใน RAM (memory) หายเมื่อ reload/close tab ต้องการ persistence ใช้ localStorage/sessionStorage/IndexedDB