Vanilla JavaScript localStorage

— 3 minute read

permalink

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 permalink

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) permalink

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) permalink

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) permalink

Once we are done with a specific item, we can remove it, but calling removeItem and passing the key.

window.localStorage.removeItem('mood');

clear() permalink

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 permalink

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. 😞
}

View on CanIUse

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter