Sobes.tech
Junior

Explain the difference between cookies, sessionStorage, and localStorage.

sobes.tech AI

Answer from AI

Cookies, sessionStorage, and localStorage are web storage mechanisms that differ in purpose, lifespan, and data capacity.

  • Cookies: Small data fragments sent by the web server and stored on the user's computer by the web browser. They are sent with each subsequent request to the same server. Used for authentication, storing user preferences, and tracking shopping cart status.

    • Lifespan: Set at creation (can be session-based or with a specific expiration date).
    • Capacity: Limited, usually a few kilobytes (about 4 KB).
  • sessionStorage: Stores data only for a single browser session (open tab or window). Data is deleted when the tab or window is closed.

    • Lifespan: Until the tab or window is closed.
    • Capacity: Significantly larger than cookies (usually several megabytes).
  • localStorage: Stores data without an expiration date until explicitly deleted by the user or script. Accessible across all tabs and windows of the same domain.

    • Lifespan: Permanent (until explicitly deleted).
    • Capacity: Significantly larger than cookies (usually several megabytes).

Here is a brief comparison:

Mechanism Lifespan Accessibility Sent to server Typical size Purpose
Cookies Session or expiration-based Via HTTP headers Yes ~4 KB Authentication, tracking, preferences
sessionStorage Until tab/window is closed Via JS API No ~5-10 MB Temporary session data storage
localStorage Permanent (until deletion) Via JS API No ~5-10 MB Long-term data storage

Examples of JavaScript API usage:

// Cookies (access via document.cookie, requires manual parsing and serialization)
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";

// sessionStorage
sessionStorage.setItem('id', '123');
let userId = sessionStorage.getItem('id');
sessionStorage.removeItem('id');

// localStorage
localStorage.setItem('theme', 'dark');
let userTheme = localStorage.getItem('theme');
localStorage.removeItem('theme');
localStorage.clear(); // Clears all data in localStorage