Learn client-side data storage options for web applications.
Example demonstrating Local Storage and Session Storage usage:
// Save data to Local Storage
localStorage.setItem('username', 'BashaRam');
// Retrieve data from Local Storage
const user = localStorage.getItem('username');
console.log('Local Storage username:', user);
// Remove data from Local Storage
localStorage.removeItem('username');
// Save data to Session Storage
sessionStorage.setItem('sessionID', 'abc123');
// Retrieve data from Session Storage
const session = sessionStorage.getItem('sessionID');
console.log('Session Storage sessionID:', session);
// Clear all Session Storage data
sessionStorage.clear();
This code demonstrates:
Local Storage: Stores data with no expiration time. Data persists even after the browser is closed and reopened. It is useful for saving user preferences or app state between sessions.
Session Storage: Stores data only for the duration of the page session. Data is cleared when the page session ends (e.g., tab or browser is closed). Suitable for temporary data needed during a browsing session.
Both use key-value pairs and store data as strings. They offer a synchronous API, making them easy to use but not suitable for large amounts of data or complex data structures without serialization.
Q1: Which of the following statements about Local Storage is true?
Answer: B. Data persists even after the browser is closed and reopened.
Q2: When does Session Storage data get cleared?
Answer: B. When the user closes the tab or browser window
Q3: How is data stored in Local and Session Storage?
Answer: C. As string key-value pairs
Q4: Which Web Storage API would you use to store user preferences that should remain after the browser is closed?
Answer: B. Local Storage