Cookie. localStorage and sessionStorage are used to data strogae on client side. In HTML5, introduced web storage such as localStorage or sessionStorage.
Web storage objects localStorage and sessionStorage used to store the data in the browser in key/value, key and value must be strings. Cookies (web cookie, browser cookie) are small text files, data stored as name-value pairs on visitor's browsers.
Both localStorage and sessionStorage are use key-value pair.
//store the data localStorage.setItem('key','value'); //retrieve the data/value: localStorage.getItem('key'); //update the data/value (same as store the data): localStorage.setItem('key','value'); //remove the item localStorage.removeItem('key'); //clear all the data: localStorage.clear();
localStorage.setItem('name','Vipin Katiyar'); localStorage.getItem('name'); localStorage.removeItem('name'); localStorage.clear(); Example 2- data store like object access //store the data localStorage.name = 'Vipin Katiyar'; //retrieve the data alert(localStorage.name ); // Vipin Katiyar //remove the key delete localStorage.name;
// for objects used JSON because it's store only string values var person = { name: 'Vipin Katiyar', age: '32 Years', qualification: 'MCA' } localStorage.setItem('person',JSON.stringify( person )); //retrieve the data of objects: var person = JSON.parse( localStorage.getItem( 'person' ) ); alert(person.name); // Vipin Katiyar
Cookies | localStorage | sessionStorage | |
---|---|---|---|
Expires | Manually set | No | Yes(Tab closed) |
Accessible/Storage | server-side/client-side | client-side | client-side |
Clear/Delete | PHP, JS and Automatic | JS | JS and Automatic |
Secured | No | No | No |
SSL Support | Yes | No | No |
Data Transfer on HTTP Request | Yes | No | No |
Browser support | Old/Latest | Latest | Latest |
Data Accessible on Client Side | Window | Current tab | Window |
Maximum Sata Size | 4 KB | 5-10 MB | 5 MB |
Related
String Concatenation in JavaScript