HTML5 Local Storage

Local storage is a replacement for cookies in js. If cookies can store data then why local storage then? One of the main reason is you can store upto 5MB of data in browser whereas in cookies the maximum limit is 4kb.

You can store data in form of key-value pair.Lets jump in to coding!!!

localStorage.setItem("Name", "Andrew");

You can access tha value as you access value of property in object.

localStorage.Name

It will return "Andrew"

There is one method for getting value of key

localStorage.getItem("Name");

It will also return the same "Andrew".

You can also clear data stored in local storage using clear() method.

localStorage.clear();

If you want to remove a particular key value pair you can use removeItem() method of local storage.

localStorage.removeItem("Name");

You can access particular key using key() method. Remember local storage data in alphabetical order so if it has tow key-value pair like

localStorage.setItem("Name", "Andrew");
localStorage.setItem("Color", "Blue");

localStorage.key(0); // return Color
localStorage.key(1);// return Name

According to alphabetical order key(0) will return Color & key(1) will return Name

Note : Key method only returns key no value.

You can also use session storage if you want the data to be maintained until the browser window closes. And the best part is you can use same methods in sessionStorage.


734 0 3