DOM — localStorage - odigity/academy GitHub Wiki

localStorage is one of the features of the Web Storage DOM API. It provides a persistent key/value data store that is only accessible by apps on the same domain, and will survive both a page refresh or a computer reboot.

All keys and values are stored as strings. If you want to store complex data structures, use JSON to serialize/deserialize them to and from strings.

The localStorage API is accessed via the localstorage property on the window object.

localStorage.clear()       -> delete all items in the store
localStorage.getItem(k)    -> return that key's value
localStorage.key(n)        -> returns the name of the nth key in the store
localStorage.length        -> returns an integer representing the number of stored items
localStorage.removeItem(k) -> remove that key from the store
localStorage.setItem(k, v) -> add that key to the store, or update that key's value if it already exists

To iterate through all items in the store:

for ( var i = 0, len = localStorage.length; i < len; ++i ) {
    console.log( localStorage.getItem( localStorage.key(i) ) );
}

Using JSON to serialize/deserialize:

var myArray = [ 1, 2, 3 ];
localStorage.setItem( 'mykey', JSON.stringify(myArray) );
var stillMyArray = JSON.parse( localStorage.getItem('mykey') );