Skip to content

Commit 8094dee

Browse files
author
Varun Yadav
committed
added Difference-between-localStorage-sessionStorage-cookies
1 parent 1c958b8 commit 8094dee

2 files changed

Lines changed: 162 additions & 1 deletion

File tree

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
### **How LocalStorage, SessionStorage, and Cookies Differ**
2+
3+
LocalStorage, sessionStorage, and cookies are all mechanisms to store data on the client-side in a web browser. They are widely used in web development to persist user data. However, each serves different purposes and has distinct characteristics.
4+
5+
---
6+
7+
### **Overview of Differences**
8+
9+
| Feature | **localStorage** | **sessionStorage** | **Cookies** |
10+
| ----------------- | ---------------------------------------------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
11+
| **Scope** | Persistent storage available across sessions. | Storage for the duration of the session. | Used for small amounts of data, sent with every HTTP request. |
12+
| **Capacity** | ~5-10 MB (varies by browser). | ~5-10 MB (varies by browser). | ~4 KB. |
13+
| **Expiration** | Data persists until manually cleared. | Data is cleared when the tab or window is closed. | Can be set with an expiration date or session-only. |
14+
| **Accessibility** | Accessible from JavaScript only. | Accessible from JavaScript only. | Accessible from both JavaScript and the server. |
15+
| **Data Storage** | Key-value pairs (string format). | Key-value pairs (string format). | Key-value pairs (string format). |
16+
| **HTTP Requests** | Not sent with HTTP requests. | Not sent with HTTP requests. | Sent with every HTTP request (unless `HttpOnly` is set). |
17+
| **Security** | Subject to JavaScript-based security measures. | Subject to JavaScript-based security measures. | Vulnerable to theft if not properly secured (e.g., `HttpOnly`, `Secure`, and `SameSite` flags). |
18+
19+
---
20+
21+
### **1. localStorage**
22+
23+
#### **Description:**
24+
25+
- `localStorage` is designed for persistent storage of data across browser sessions.
26+
- Data is not automatically cleared unless explicitly removed by the user or application.
27+
28+
#### **Features:**
29+
30+
- Stores data in key-value pairs.
31+
- Supports string values only (objects must be stringified before storage).
32+
33+
#### **Use Cases:**
34+
35+
- Storing user preferences (e.g., theme settings, language preferences).
36+
- Caching data for offline usage (e.g., progressive web apps).
37+
38+
#### **Example:**
39+
40+
```javascript
41+
// Save data
42+
localStorage.setItem("username", "Varun");
43+
44+
// Retrieve data
45+
console.log(localStorage.getItem("username")); // Output: Varun
46+
47+
// Remove data
48+
localStorage.removeItem("username");
49+
```
50+
51+
---
52+
53+
### **2. sessionStorage**
54+
55+
#### **Description:**
56+
57+
- `sessionStorage` stores data for the duration of the browser session.
58+
- Data is cleared when the tab or browser window is closed.
59+
60+
#### **Features:**
61+
62+
- Similar to `localStorage`, but limited to the session's lifetime.
63+
64+
#### **Use Cases:**
65+
66+
- Temporary storage of data specific to a session (e.g., shopping cart items for an ongoing session).
67+
- Storing data that should not persist beyond the session.
68+
69+
#### **Example:**
70+
71+
```javascript
72+
// Save data
73+
sessionStorage.setItem("sessionId", "abc123");
74+
75+
// Retrieve data
76+
console.log(sessionStorage.getItem("sessionId")); // Output: abc123
77+
78+
// Remove data
79+
sessionStorage.removeItem("sessionId");
80+
```
81+
82+
---
83+
84+
### **3. Cookies**
85+
86+
#### **Description:**
87+
88+
- `Cookies` are small pieces of data stored in the browser and sent with every HTTP request to the server.
89+
- They are traditionally used for session management, authentication, and tracking.
90+
91+
#### **Features:**
92+
93+
- Can include attributes like `HttpOnly`, `Secure`, and `SameSite` for added security.
94+
- Limited in size (usually up to 4 KB).
95+
- Accessible by both the server and the client (if `HttpOnly` is not set).
96+
97+
#### **Use Cases:**
98+
99+
- Session management (e.g., user login sessions).
100+
- Personalization and tracking (e.g., storing user preferences, analytics).
101+
102+
#### **Example:**
103+
104+
```javascript
105+
// Set a cookie
106+
document.cookie =
107+
"username=Varun; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";
108+
109+
// Retrieve cookies
110+
console.log(document.cookie); // Output: username=Varun
111+
112+
// Delete a cookie (set expiration in the past)
113+
document.cookie =
114+
"username=Varun; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
115+
```
116+
117+
---
118+
119+
### **Key Differences Explained**
120+
121+
1. **Persistence:**
122+
123+
- `localStorage` persists indefinitely until manually removed.
124+
- `sessionStorage` lasts only for the current session.
125+
- `Cookies` can persist based on the expiration date or be session-based.
126+
127+
2. **Size:**
128+
129+
- `localStorage` and `sessionStorage` have a much larger capacity (~5-10 MB) compared to cookies (~4 KB).
130+
131+
3. **Server Communication:**
132+
133+
- `localStorage` and `sessionStorage` do not communicate with the server.
134+
- `Cookies` are sent with every HTTP request, adding to the request size.
135+
136+
4. **Security:**
137+
- `Cookies` can be secured using `HttpOnly`, `Secure`, and `SameSite` flags to prevent theft and misuse.
138+
- `localStorage` and `sessionStorage` are less secure as they are accessible via JavaScript and prone to XSS (Cross-Site Scripting) attacks.
139+
140+
---
141+
142+
### **When to Use Which?**
143+
144+
- **localStorage:** For data that needs to persist across sessions and does not require server-side interaction (e.g., user preferences).
145+
- **sessionStorage:** For temporary data that is relevant only during the current session (e.g., form input data).
146+
- **Cookies:** For server-side session management, authentication tokens, or tracking purposes.
147+
148+
---
149+
150+
### **Best Practices**
151+
152+
1. Avoid storing sensitive data (e.g., passwords) in any client-side storage.
153+
2. Use `HttpOnly` and `Secure` flags with cookies for better security.
154+
3. Minimize the use of cookies for non-essential data to reduce HTTP request size.
155+
4. Sanitize and validate all inputs to prevent XSS attacks.
156+
157+
---
158+
159+
### **Conclusion**
160+
161+
While `localStorage`, `sessionStorage`, and cookies all serve as client-side storage mechanisms, they differ significantly in terms of persistence, security, size, and purpose. Choosing the appropriate mechanism depends on the use case, data sensitivity, and interaction with the server. Understanding these differences is essential for building secure and efficient web applications.

‎Hard/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ This section contains advanced JavaScript interview questions. Click on each que
88
4. [How can you remove duplicates from an array in JavaScript?](Remove-duplicates-from-array.md)
99
5. [What is memoization in JavaScript?](Memoization-in-JS.md) ✅
1010
6. [What is the difference between innerHTML and innerText?](Difference-between-innerHTML-and-innerText.md) ✅
11-
7. [Explain how localStorage, sessionStorage, and cookies differ.](Difference-between-localStorage-sessionStorage-cookies.md)
11+
7. [Explain how localStorage, sessionStorage, and cookies differ.](Difference-between-localStorage-sessionStorage-cookies.md) ✅
1212
8. [What is destructuring in JavaScript, and how does it work?](Destructuring-in-JS.md) ✅
1313
9. [How can we handle callback hell situations?](Handling-callback-hell.md)
1414
10. [Explain Default and Named Exports.](Default-and-named-exports.md)

0 commit comments

Comments
 (0)