Last Updated: June 26, 2023
·
237.9K
· jfsagasti

Storing and retrieving objects with localStorage [HTML5]

Today I've played with this great feature of HTML5 for the first time. It was pretty straighforward and comfortable.

localStorage stores key-value pairs. So to store a entire javascript object we need to serialize it first (with JSON.stringify, for example):

localStorage.setItem('user', JSON.stringify(user));

Then to retrieve it from the store and convert to an object again:

var user = JSON.parse(localStorage.getItem('user'));

If we need to delete all entries of the store we can simply do:

localStorage.clear();

You can find JSON library to stringify and parse the objects here:

http://json.org/