How to use Local Storage in JavaScript?

localStorage is another web storage in HTML5 specification. By 2022 when this article is being written, It is supported by almost all browsers including IE8. If you think your web app or website will be accessed by a very old browser or a browser that does not support localStorage, you can do a quick check if the browser supports localStorage.

if ( typeof(Storage) !== "undefined" ) {
    // localStorage is supported. 
} 
else {
    // localStorage not supported 
}

I will discuss localStorage in detail but let’s see a quick example.
Setting localStorage value.

localStorage.setItem('name', 'John Doe');

or

let person = {
    name        : "John Doe",
    location    : "New York",
}
window.localStorage.setItem( 'user', JSON.stringify(person) );


Getting stored value from localStorage.

localStorage.getItem('user');

This will return a string with the value:

“{“name”:“John Doe”,“location”:“New York”}”

Now you can convert the string back to an object using JSON.parse().

JSON.parse( localStorage.getItem('user') );


Let’s jump into a detailed discussion!

What is localStorage?