Vanilla JavaScript localStorage

β€” 4 minute read

permalink

Now and then, during web development it would help if you stored a small variable in the frontend for later use. It might be, for instance, a cookie bar status, a shopping cart, or whatever.

To do that, we can use the localStorage API JavaScript. Let's learn how to use it.

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 the method to the test and set and retrieve data.

Set an Item with setItem(key, value) permalink

To set an item with a specific value for a key we can do the following:

window.localStorage.setItem('mood', 'πŸ˜ƒ');

To store data like an object we can use this code:

const person = {
name: 'Chris',
mood: '🀩'
};
window.localStorage.setItem('person', JSON.stringify(person));

Get data with getItem(key) permalink

To get data from an item in localstorage we need the key we used to identify the data:

console.log(window.localStorage.getItem('mood')); // πŸ˜ƒ

Or for an Object:

console.log(JSON.parse(window.localStorage.getItem('person'))); // {name: "Chris", mood: "🀩"}

Remove Item from localstorage with removeItem(key) permalink

Once we are done with a specific item, we can remove it. We simply call removeItem and pass the key.

window.localStorage.removeItem('mood');

Clear item with clear() permalink

When we want to clear all items from the localStorage, we can use the clear method:

window.localStorage.clear();

See the localstorge examples in this Codepen permalink

Feel free to play around with the example code on 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