Manipulating Storage Data

Data saved in Web Storage is stored as key/value pairs.

A few examples of simple key/value pairs:
■ key: name, value: Fernando
■ key: painter, value: David
■ key: email, value:

Setting the data

(I) sessionStorage
To store some data for only the current browser instance (goes away when the user closes the browser), use sessionStorage

var user_id = "A1B2C3D4";
var user_data = {
name: "Tom Hanks",
occupation: "Actor",
favorite_color: "Blue"
// ...
sessionStorage.setItem(user_id, JSON.stringify(user_data));

(II) localStorage
To store some data for a longer period of time, use localStorage

var user_id = "A1B2C3D4";
var user_prefs = {
keep_me_logged_in: true,
start_page: "daily news"
// ...
localStorage.setItem(user_id, JSON.stringify(user_prefs));

Shortcut Way:-
Instead of localStorage.setItem(key, value), we can say localStorage[key]= value: localStorage["size"] = 6;

localStorage.setItem(key, value)


localStorage[key]= value

Getting the data
To pull data from the storage container:

var user_id = "A1B2C3D4";
var user_data = { /* defaults */ };
var user_prefs = { /* defaults */ };
if (sessionStorage.getItem(user_id)) {
user_data = JSON.parse(sessionStorage.getItem(user_id));
if (localStorage.getItem(user_id)) {
user_prefs = JSON.parse(localStorage.getItem(user_id));

These Storage APIs allow you to very simply set and retrieve key/value data, where the value is a string, but can represent anything you want, including the string serialization of a complex data object.

Shortcut Way:-
Instead of localStorage.getItem(key), we can simply say localStorage[key].

var size = localStorage["size"];

Removing Items and Clearing Data

removeItem(key)To remove a specific item from Web Storage, we can use the removeItem method.
We pass it the key we want to remove, and it will remove both the key and its value.
To remove all data stored by our site on a user's computer, we can use the clear
method. This will delete all keys and all values stored for our domain.

Related Tutorial