DEV Community

Cover image for Local Storage In Javascript
Neeraj Kumar
Neeraj Kumar

Posted on

Local Storage In Javascript

HTML5 provides a feature to store data locally in end user’s browser. Data is stored in the browser as key-value pair. Unlike cookie it has average space of 5 MB. This storage comes in 2 different type sessionStorage and localStorage.

localStorage: it stores data with no expiration date.
sessionStorage : it stores data withan expiration date.

Which one is the main Storage interface?
window.Storage()is the main interface from where the localStorage and sessionStorage are implemented. This interface has the below definition.

interface Storage {
readonly attribute unsigned long length;
DOMString? key(unsigned long index);
getter DOMString? getItem(DOMString key);
setter creator void setItem(DOMString key, DOMString value); deleter void removeItem(DOMString key);
void clear();
}
setItem(key,value): This methods stored the value in storage using key-value pair.
getItem(key) : This method retrieves the stored object using the key.
removeItem(key) : This methods removes the stored item based on the key.
clear() : Deletes all the items from the storage. length : This property returns the length of the storage, no of elements inside the storage.
key(position) : This method returns the key for the value in the given numeric position.

How to store and retrieve an object in local storage?

Local storage provides setItem() and getItem() for storing and retrieving an object from
the storage. setItem(key, value) method takes 2 input parameter to store the object. The
getItem(key) method retrieves the value using key as input parameter. Below code shows
the storing “Neeraj Kumar” string in “myName” key and then retrieves this string
place it in a HTML element.

<!DOCTYPE html>
<html>
<body>
<div id=“resultContainer”>
</div>
<script>
var container =
document.getElementById(“resultContainer”);
localStorage.setItem(“myName”, “Neeraj kumar”); 
container.innerHTML =localStorage.getItem(“myName”); 
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

How to attach an event to a local storage?
When local storage objects get modified a storage event is fired. A callback method can be
attached to window object using addEventListener() or attachEvent() method.

Both storage objects provide same methods and properties:

setItem(key, value) – store key/value pair.
getItem(key) – get the value by key.
removeItem(key) – remove the key with its value.
clear() – delete everything.
key(index) – get the key on a given position.
length – the number of stored items.
As you can see, it’s like a Map collection (setItem/getItem/removeItem), but also allows access by index with key(index).

Top comments (0)