How to store and read data using localStorage in Javascript?


When we develop website applications, we may need to store and read some data for a long time, but it is quite cumbersome to save it to the machine in the form of files. At this time, we can use localStorage in Javascript to access data. In this post you will learn: ① How to use localStorage?  ② How to save and read strings via localStorage? ③ How to store and read Json objects through localStorage?

Keywords: Javascript , cookie data , localStorage , setItem , getItem.

Basic use of localStorage

Data in javascript can be easily accessed using the localStorage.setItem() and localStorage.getItem() functions. It should be noted that when using localStorage.getItem(), it is necessary to determine whether the data of the given name exists.

					//store data
localStorage.setItem('id', id);

//read data, verify existing is nedded
if (localStorage.getItem('id') != null) {
	var id=localStorage.getItem('id');

//clear all storage
//clear specify storage


Json objects

When using localStorage to save a Json object, you need to format the Json object as a string with JSON.stringify() before storing, and after reading the Json object cache, you need to reformat it with JSON.parse().

					//store json object
//JSON.stringify() is nedded
var data={"id":1,"name":"test_json_object"};
var content = JSON.stringify(data);
localStorage.setItem('test_json_object', content);

//read json object
//JSON.parse() is nedded
if (localStorage.getItem('test_json_object') != null) {
	var saved_test_json_object= JSON.parse(localStorage.getItem("test_json_object"));


Accessing data in the website can be achieved by using setItem(), getItem(), clear(), removeItem() of localStorage. It should be noticed that when processing Json objects, you need to combine JSON.stringify() and JSON.parse () to format the data.

Related articles

Coming soon

If yuo have any question or need any help 

you can leave a comment or connect me with

Edit Template

Leave a Reply

Your email address will not be published. Required fields are marked *

Chaoxu Wei

Master student at Tongji University (Writer & Blogger)

Job hunting, both part-time and full-time jobs are accepted. Job recommendation please email me, thank you very much!


Edit Template

“There are many people in the world who want to work hard but can’t, and people who work too hard and are exhausted. Please don’t use your efforts only to chase your own victory, please use them to help others.”




Yangpu District, Shanghai