Vanilla JavaScript localStorage

โœ๏ธ

Today we are going to leverage the localStorage in JavaScript. We will learn how to get data from it, set data and also how to clear it.

14 Jun, 2020 ยท 2 min read

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

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)

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)

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)

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

window.localStorage.removeItem('mood');

Clear item with clear()

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

window.localStorage.clear();

See the local storage examples in this Codepen

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

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!

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API