Javascript How to store data in local storage?

Last updated May 08, 2021

In this Javascript Local storage example we will cover how to store and retrieve data from local storage. What is local storage? Local storage properties allows user to store data in key value pairs in the web browser. This local storage object stores the data without expiration date. This local storage data will not be deleted when we close the window. This local storage will be a read only property.

Let's check simple Javascript local storage example

Create simple html file which contains a input fields to enter key and values and one button to save the data.




Javascript Local Storage


Insert Data

Insert Data




How to store data in Local Storage?

To store data on Local Storage browser we need to use localStorage object. To store the each data item we need to pass key and value to the setItem() method.




How to fetch data from Local Storage?

To fetch the data from the local storage first we need to fetch all keys first then fetch the values by passing the key to localStorage.getItem(key) method.


for(let k=0;k {
const key=localStorage.key(k);
const value=localStorage.getItem(key);
outputinp.innerHTML +=key+":"+value+"




How to delete data from Local Storage?

To delete the specific key item data from the local storage we will use localStorage.removeItem(key) method by passing the key name.


localStorage.removeItem("key Name")


Javascript Local Storage



Complete example

<title>Javascript Local Storage</title>

<h2>Javascript Local Storage</h2>

<legend>Insert Data</legend>
<input type="text" id="key" placeholder="Enter Key..."/>
<input type="text" id="value" placeholder="Enter Value..."/>
<button type="button" id="btn">Insert Data</button>


<legend>Fetach Local Storage Data:</legend>
<div id="output">



const keyinp=document.getElementById("key");
const valueinp=document.getElementById("value");
const btninp=document.getElementById("btn");
const outputinp=document.getElementById("output");


const key=keyinp.value;
const value=valueinp.value;





for(let k=0;k<localStorage.length;k++)
const key=localStorage.key(k);
const value=localStorage.getItem(key);
outputinp.innerHTML +=key+" : "+value+"<br /><br />";



Conclusion: In this example we learned how to store data in local storage in javscript, and retrieve and delete data from local storage object.


Article Contributed By :


Subscribe For Daily Updates

Flutter Questions
Android Questions