localStorage and sessionStorage, part of the web storage API, are two great tools to save key/value pairs locally. If you click the save button at the top of this post, localStorage is what’s used to store your saved posts.
You may also like: What’s the Difference Between Local, Session Storage and Cookies?.
Both localStorage and sessionStorage offer advantages compared to using cookies:
It’s also supported in all modern browsers, so you can use it today without an issue. Obviously, since the data can’t be read on the server, cookies still have a use, especially when it comes to authentication.
localStorage and sessionStorage accomplish the exact same thing and have the same API, but with sessionStorage the data is persisted only until the window or tab is closed, while with localStorage the data is persisted until the user manually clears the browser cache or until your web app clears the data. The examples in this post are for localStorage, but the same syntax works for sessionStorage.
Create key/value pair entries with localStorage.setItem, providing a key and a value:
let key = 'Item 1';
localStorage.setItem(key, 'Value');
Read entries with localStorage.getItem:
let myItem = localStorage.getItem(key);
Update an entry just as you would create a new one with setItem, but with a key that already exists:
localStorage.setItem(key, 'New Value');
Delete an entry with the removeItem method:
localStorage.removeItem(key);
Here’s how to clear everything that’s stored in localStorage:
localStorage.clear();
Only strings can be stored with localStorage or sessionStorage, but you can use JSON.stringify to store more complex objects and JSON.parse to read them:
// Create item:
let myObj = { name: 'Skip', breed: 'Labrador' };
localStorage.setItem(key, JSON.stringify(myObj));
// Read item:
let item = JSON.parse(localStorage.getItem(key));
Here’s how you can test for the presence of items in the loclaStorage:
if (localStorage.length > 0) {
// We have items
} else {
// No items
}
Test for localStorage support by checking if it’s available on the window object:
if (window.localStorage) {
// localStorage supported
}
localStorage or sessionStorage don’t have a forEach method, but you can iterate over the items with a good old for loop:
for (let i = 0; i < localStorage.length; i++){
let key = localStorage.key(i);
let value = localStorage.getItem(key);
console.log(key, value);
}
Thank you for reading!
#html #programming #developer #javascript