LocalStorage is a type of web storage that allows JavaScript sites and apps to store and access data with no expiration date. This means the data persists even after the browser window is closed, making it useful for storing information such as shopping cart data or user login details.
• Persistence: Data stored in localStorage does not expire.
• Storage Limit: LocalStorage has a higher storage limit than cookies (5MB vs. 4MB).
• Security: LocalStorage is not secure for sensitive data as it can be accessed by any code running on the page.
• Usage: Data stored in localStorage remains on the browser and is not sent with every HTTP request, unlike cookies.
LocalStorage offers several methods for interacting with the stored data. Here are the primary methods:
| Method | Description |
|---|---|
| setItem() | Adds data to localStorage using a key-value pair. |
| getItem() | Retrieves the value from localStorage using a key. |
| removeItem() | Removes an item from localStorage using a key. |
| clear() | Clears all data from localStorage. |
To add data to localStorage, both a key and a value are required:
localStorage.setItem("city", "Pune");
To retrieve data, only the key is needed:
const res = localStorage.getItem("city");
console.log(res); // Output: Pune
To remove a specific item, use the key:
localStorage.removeItem("city");
To clear all data from localStorage:
localStorage.clear();
• Security: LocalStorage is not secure for storing sensitive information like usernames and passwords.
• Data Protection: There is no data protection in localStorage.
• Storage Limit: The maximum storage limit is 5MB.
• Synchronous Nature: Operations in localStorage are synchronous, meaning each operation executes one after another.
• Persistence: Data does not expire and remains available even after closing the browser.
• Ease of Use: Methods like setItem(), getItem(), removeItem(), and clear() are simple to use.
• No HTTP Overhead: Unlike cookies, localStorage data is not sent with every HTTP request.
• Higher Storage Limit: LocalStorage can store more data than cookies (5MB vs. 4MB).
<script>
// Add data to localStorage
localStorage.setItem("city", "Pune");
localStorage.setItem("country", "India");
// Retrieve data from localStorage
const city = localStorage.getItem("city");
const country = localStorage.getItem("country");
// Display data using document.write
document.write("<p>City: " + city + "</p>");
document.write("<p>Country: " + country + "</p>");
// Clear all localStorage data
localStorage.clear();
</script>
City: Pune
Country: India