Sobes.tech
Junior

Explain the difference between cookies, sessionStorage, and localStorage.

sobes.tech AI

Answer from AI

Cookies store small amounts of text information (up to 4KB) on the client side, sent with each HTTP request to the domain that set them. They can have an expiration date. Used for authentication, user tracking, and saving user preferences.

localStorage stores data without an expiration date (until the user clears storage or deletes the browser) on the client side (up to 5-10MB depending on the browser). Data is accessible between browser sessions, but only for scripts of the same origin (domain, protocol, port). They are not sent automatically with HTTP requests. Used for long-term data storage and application settings.

sessionStorage stores data for the duration of a single browser session (as long as the tab or window is open). Data is deleted when the tab or window is closed. Storage capacity is similar to localStorage (up to 5-10MB). Data is also only accessible to scripts of the same origin. They are not sent automatically with HTTP requests. Used for temporary data storage specific to the current session.

Characteristic Cookies localStorage sessionStorage
Storage duration Expiration date or browser close Until deleted by user/application Until the tab/window is closed
Data size Up to 4KB Up to 5-10MB Up to 5-10MB
Accessibility Sent with HTTP requests to the domain Only accessible via JavaScript of the same origin Only accessible via JavaScript of the same origin
Accessibility between tabs Yes Yes No (for different tabs)
Purpose Authentication, tracking, preferences Long-term storage, settings Temporary storage within a session

Example of using localStorage:

// Save data
localStorage.setItem('userName', 'Alice');

// Retrieve data
const userName = localStorage.getItem('userName');
console.log(userName); // Output: Alice

// Remove data
// localStorage.removeItem('userName');

// Clear all storage
// localStorage.clear();

Example of using sessionStorage:

// Save data
sessionStorage.setItem('orderId', '12345');

// Retrieve data
const orderId = sessionStorage.getItem('orderId');
console.log(orderId); // Output: 12345

// Remove data
// sessionStorage.removeItem('orderId');

// Clear all storage
// sessionStorage.clear();