DEV Community

Cover image for How to use localStorage API
Amer Sikira
Amer Sikira

Posted on • Originally published at webinuse.com

How to use localStorage API

This post was originally published on webinuse.com
Probably, one of the easiest, to understand, JavaScript APIs is the localStorage API. Also, it is not only simple, but it is pretty effective and straightforward. localStorage is property of window object that allows us to work with Storage. Unlike sessionStorage, localStorage is permanent storage. This means that data will remain intact until we delete it or change it.

All of the modern browsers fully support localStorage.

caiuse.com screenshot of localStorage JavaScript API support

Saving data to localStorage

The first thing, probably, that we will ever do is to save something to localStorage. Items are saved like key-value. Only String can be saved into localStorage. But that does not prevent us from saving anything we want, there.

As we have mentioned earlier, only strings can be saved to localStorage. If we pass an iterger, it will convert to string. If we want to pass an object, we have to use JSON.stringify.

Getting data from storage

Getting data from storage is as simple as saving. We only use one command localStorage.getItem('key'); We use the same key that we have used when we saved an item to storage.

Update key in storage

Updating keys in localStorage is same as creating new.

Remove key from localStorage

Sometimes we need to delete some key. We can do this by using localStorage.removeItem("key"). This command completely deletes key from storage.

If we want to clear entire localStorage, we can use following method: localStorage.clear(). As a result, everything from localStorage will be deleted, for current domain.

Additional information

Like Cookies and sessionStorage, localStorage is linked to the domain. If the key is missing it will return null.

If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like CSS Positions, the complete guide.

Top comments (0)