Day 20 - A Friendly Guide to LocalStorage and SessionStorage in JavaScript
Screenshot:-
Hey there! Have you ever wondered how websites remember your preferences or keep you logged in even after you close the tab? Well, that's where LocalStorage and SessionStorage come into play. In this article, we’ll dive into these two fantastic tools provided by JavaScript, and by the end, you'll be a storage expert!
What are LocalStorage and SessionStorage?
LocalStorage and SessionStorage are both part of the Web Storage API, which allows us to store data in the browser. This means we can save data that persists across different page loads and sessions, making our web applications more powerful and user-friendly.
LocalStorage
Persistent Storage: Data in LocalStorage doesn’t expire. It remains until explicitly deleted.
Storage Limit: Usually around 5MB, but it can vary between browsers.
Shared Across Tabs: Data stored is accessible from any tab of the same origin.
SessionStorage
Session-Specific Storage: Data in SessionStorage is limited to the lifetime of the page session. Once the tab is closed, the data is gone.
Storage Limit: Also around 5MB.
Isolated per Tab: Data is only accessible within the same tab, making it perfect for storing temporary data.
How to Use LocalStorage and SessionStorage
1. Saving Data
Saving a simple string value:
// LocalStorage
localStorage.setItem('myKey', 'Hello, LocalStorage!');
// SessionStorage
sessionStorage.setItem('myKey', 'Hello, SessionStorage!');
2. Retrieving Data
Fetching the saved string value:
// LocalStorage
let localValue = localStorage.getItem('myKey');
console.log(localValue); // Output: Hello, LocalStorage!
// SessionStorage
let sessionValue = sessionStorage.getItem('myKey');
console.log(sessionValue); // Output: Hello, SessionStorage!
3. Removing Data
Removing a specific item:
// LocalStorage
localStorage.removeItem('myKey');
// SessionStorage
sessionStorage.removeItem('myKey');
4. Clearing All Data
Clearing all stored data:
// LocalStorage
localStorage.clear();
// SessionStorage
sessionStorage.clear();
5. Working with Objects
Since LocalStorage and SessionStorage only store strings, we need to convert objects to JSON strings before saving them.
Saving an Object:
let user = { name: 'John Doe', email: 'john.doe@example.com' };
// LocalStorage
localStorage.setItem('user', JSON.stringify(user));
// SessionStorage
sessionStorage.setItem('user', JSON.stringify(user));
Retrieving an Object:
// LocalStorage
let retrievedUser = JSON.parse(localStorage.getItem('user'));
console.log(retrievedUser); // Output: { name: 'John Doe', email: 'john.doe@example.com' }
// SessionStorage
let retrievedSessionUser = JSON.parse(sessionStorage.getItem('user'));
console.log(retrievedSessionUser); // Output: { name: 'John Doe', email: 'john.doe@example.com' }
Practical Examples
1. Saving User Input with LocalStorage
Let's create a simple form that saves the user’s name and email to LocalStorage and retrieves it when the page is reloaded.
<!DOCTYPE html>
<html>
<body>
<form id="userForm">
Name: <input type="text" id="name" required><br>
Email: <input type="email" id="email" required><br>
<input type="submit" value="Save">
</form>
<div id="savedData"></div>
<script>
document.getElementById('userForm').addEventListener('submit', function(event) {
event.preventDefault();
let name = document.getElementById('name').value;
let email = document.getElementById('email').value;
localStorage.setItem('userName', name);
localStorage.setItem('userEmail', email);
displaySavedData();
});
function displaySavedData() {
let name = localStorage.getItem('userName');
let email = localStorage.getItem('userEmail');
if (name && email) {
document.getElementById('savedData').innerHTML = `Name: ${name}, Email: ${email}`;
}
}
window.onload = displaySavedData;
</script>
</body>
</html>
2. Saving User Input with SessionStorage
Here’s how you can do the same with SessionStorage:
<!DOCTYPE html>
<html>
<body>
<form id="sessionForm">
Name: <input type="text" id="sessionName" required><br>
Email: <input type="email" id="sessionEmail" required><br>
<input type="submit" value="Save">
</form>
<div id="sessionSavedData"></div>
<script>
document.getElementById('sessionForm').addEventListener('submit', function(event) {
event.preventDefault();
let name = document.getElementById('sessionName').value;
let email = document.getElementById('sessionEmail').value;
sessionStorage.setItem('sessionUserName', name);
sessionStorage.setItem('sessionUserEmail', email);
displaySessionSavedData();
});
function displaySessionSavedData() {
let name = sessionStorage.getItem('sessionUserName');
let email = sessionStorage.getItem('sessionUserEmail');
if (name && email) {
document.getElementById('sessionSavedData').innerHTML = `Name: ${name}, Email: ${email}`;
}
}
window.onload = displaySessionSavedData;
</script>
</body>
</html>
Comparing LocalStorage and SessionStorage
Feature | LocalStorage | SessionStorage |
Persistence | Until manually deleted | Until the tab is closed |
Storage Limit | Around 5MB (varies by browser) | Around 5MB (varies by browser) |
Accessibility | Accessible across all tabs | Accessible only within the same tab |
Use Case | Storing user preferences, login info | Storing temporary data, session info |
Key Points to Remember:
LocalStorage is best for storing data that needs to persist across multiple sessions (like user preferences).
SessionStorage is perfect for data that should only last for the duration of the page session (like a one-time form submission).
Conclusion
Understanding LocalStorage and SessionStorage is essential for building modern web applications that require data persistence. They provide a simple yet powerful way to store data in the browser, making your applications more responsive and user-friendly. So, go ahead and start experimenting with these storage mechanisms in your projects!
Happy coding!
Subscribe to my newsletter
Read articles from Alpit Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Alpit Kumar
Alpit Kumar
I am a passionate web developer and open-source enthusiast on a captivating journey of coding wonders. With a year of experience in web development, my curiosity led me to the enchanting world of React, where I found a true calling. Embracing the magic of collaboration and knowledge-sharing, I ventured into the realm of open source, contributing to Digital Public Goods (DPGs) for the betterment of the digital universe. A firm believer in learning in public, I share my insights and discoveries through blogging, inspiring fellow coders to embark on their own magical coding odysseys. Join me on this thrilling adventure, where imagination and technology converge, and together, let's shape the future of the digital landscape! 🎩✨