Now and then, it would help if you stored a small variable for later on. Might be, for instance, a cookie bar status, a shopping cart, or whatever. We can use the localStorage API for this in JavaScript
.
JavaScript localStorage methods
The JavaScript localStorage comes with the following methods we can use and leverage;
-
setItem(key, value)
Allow us to set a value for a specific key we pass. -
getItem(key)
Retrieve a specific item value based on the key. -
removeItem(key)
Remove an item from localStorage based on the key. -
clear()
Clears all localStorage we setup. -
key()
Retrieves the key name on a specific number.
Let's put it to the test and set and retrieve data.
setItem(key, value)
To set a specific value for a key we can do the following:
window.localStorage.setItem('mood', '😃');
But sometimes we want to save an object we can do as such:
var person = {
name: 'Chris',
mood: '🤩'
};
window.localStorage.setItem('person', JSON.stringify(person));
getItem(key)
To retrieve an item we need the key we used to identify:
console.log(window.localStorage.getItem('mood')); // 😃
Or for the Object:
console.log(JSON.parse(window.localStorage.getItem('person'))); // {name: "Chris", mood: "🤩"}
removeItem(key)
Once we are done with a specific item, we can remove it, but calling removeItem
and passing the key.
window.localStorage.removeItem('mood');
clear()
Or if we want to clear all the localStorage, we can use the following method:
window.localStorage.clear();
Feel free to play around with this Codepen.
See the Pen Vanilla JavaScript localStorage by Chris Bongers (@rebelchris) on CodePen.
Browser Support
The browser support is relatively good we can check if the browser supports it with the following code:
if (typeof Storage !== 'undefined') {
// Yeah! It is supported. 🥳
} else {
// No web storage Support. 😞
}
Thank you for reading, and let's connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter
Top comments (4)
localStorage has many gotchas around it like different behavior in different browsers when localStorage is full also in browsers like safari you can't access or set localStorage when in incognito mode.
It all comes with downsides indeed!
Not the most reliable storage, but a good alternative to keep in mind.
Very nice quick check! Love it <3