Local and Session Storage

With the advent of HTML5, data storage on a user’s local machine is possible without the need for cookies. The localStorage object allows us to store persistent data, in a key-value pair fashion. There is also a sessionStorage object in which we can store key-value pairs, the data for which is cleared when the user closes their browser window.

Data is added to either object by assigning a value to a given property:

localStorage.foo = 'Hello World!';
console.log(localStorage.foo);
Hello World!

Removal of a key from the object is via. the removeItem method:

localStorage.removeItem(foo);

If we want to remove all keys from our localStorage/sessionStorage object, we can use the clear() method:

localStorage.clear();

We can also iterate through the localStorage/sessionStorage object’s keys using the length property and the key() method:

for(var i=0; i<localStorage.length; i++){
	var key = localStorage.key(i);
	var value = localStorage[key];

	console.log('localStorage[' + key + '] = ' + value);
}

It is also possible to assign variable keys to either object, by treating the object as an associative array:

for (var i=1; i<=10; i++) {
	localStorage['item_' + i] = i+1;
}

for(var i=0; i<localStorage.length; i++){
	var key = localStorage.key(i);
	var value = localStorage.[key];

	console.log('localStorage[' + key + '] = ' + value);
}
localStorage[item_1] = 1;
localStorage[item_2] = 2;
localStorage[item_3] = 3;
localStorage[item_4] = 4;
localStorage[item_5] = 5;
localStorage[item_6] = 6;
localStorage[item_7] = 7;
localStorage[item_8] = 8;
localStorage[item_9] = 9;
localStorage[item_10] = 10;

As web storage is not supported by older browser versions (notably IE 7 and below) we need to check for support before we begin to make use of the localStorage and sessionStorage objects:

if (typeof(Storage) !== 'undefined') {
	// Make use of web storage
}
else {
	// Fall-back code
}
Share Button