
How to Use Local Storage with JavaScript
I like making tutorials where you build a small application completely from scratch with plain JavaScript. A to-do list is a common app idea, but without having a database to store the to-dos, it’s not particularly useful, and that adds a bit of complexity beyond beginner territory.
However, even without any sort of database, we can use the local storage built into a web browser to save to-do items. This could be actually useful for taking quick notes. Set the app as your “new tab” page in your browser and the to-dos will persist on your local computer as long as you don’t clear the cache.
So that’s what we’re going to learn to do today.
Prerequisites
- Basic knowledge of HTML and CSS.
- Basic knowledge of JavaScript syntax and datatypes.
- Basic knowledge of working with the DOM (optional). The How to Connect to an API article will teach you how to make a simple web app, otherwise you can learn with this small tutorial as well.
Goals
- Create a “new tab page” application that stores to-do items locally in the browser’s local storage and displays them on the front end. View example.
Overview of web storage
Web storage is data stored locally in a user’s browser. There are two types of web storage:
- Local storage – data with no expiration date that will persist after the browser window is closed.
- Session storage – data that gets cleared after the browser window is closed.
This is useful for saving data such as user preferences (light or dark color theme on a website), remembering shopping cart items, or remembering a user is logged into a website.
Previously, cookies were the only option for remembering this type of local, temporary data. Local storage has a significantly higher storage limit (5MB vs 4KB) and doesn’t get sent with every HTTP request, so it can be a better option for client-side storage.
Here is an overview of localStorage
methods.
Method | Description |
---|---|
setItem() |
Add key and value to local storage |
getItem() |
Retrieve a value by the key |
removeItem() |
Remove an item by key |
clear() |
Clear all storage |
You can test out what’s in local storage by going to the JavaScript console and typing it in. Actually do this, don’t just read it.
localStorage
Storage {length: 0}
Adding some data to localStorage
is as easy as using the setItem()
method. I’ll use a generic key and value for the names, but they can be any strings.
localStorage.setItem('key', 'value');
Now if you test localStorage
in the console again, you’ll find your new key and value.
Storage {key: "value", length: 1}
If you want to get the value for a particular key, you’ll use the getItem()
method.
localStorage.getItem('key');
value
Finally, you can remove the data with removeItem()
.
localStorage.removeItem('key');
Using clear()
will clear all local storage.
localStorage.clear();
Now we can begin setting up the app.
Setting up the front end
First, we’ll create a simple HTML front end with index.html. I’m loading in Primitive (my minimalist CSS framework) for styles, because that’s what I always use when I need a quick front end.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>New Tab App</title>
<link rel="stylesheet" href="https://taniarascia.github.io/primitive/css/main.min.css">
</head>
<body>
<div class="small-container">
<h1>New Tab App</h1>
<!-- more will go here -->
</div>
<script src="js/scripts.js"></script>
</body>
</html>
We’re going to set up with three things:
- A text input – for adding new items.
- A list – where the items will be added on the front end.
- A button – to clear all items.
Add this code where the “more will go here” comment is.
<form>
<input id="item" type="text" placeholder="New" required>
</form>
<h2>Items</h2>
<ul></ul>
<button>Clear All</button>
Here’s what it looks like:
And that’s all for the front end. From here, we’ll focus on adding functionality with JavaScript.
The HTML presented here is simplified for demonstrative purposes, and does not account for accessibility concerns.
Setting up JavaScript functionality
Before we integrate this into local storage, let’s just get the form and list working – we want anything we submit in the input
to appear in the ul
.
First, I’m just going to set up some variables for the elements on the page – the form, the unordered list, the button, and the text input.
const form = document.querySelector('form');
const ul = document.querySelector('ul');
const button = document.querySelector('button');
const input = document.getElementById('item');
Next, I’m going to make a function that creates an li
element, since I’ll be doing that more than once. I’ll call the function liMaker()
. It just creates an li
element, sets the text of the element to the parameter, and appends the list item to the ul
.
const liMaker = (text) => {
const li = document.createElement('li');
li.textContent = text;
ul.appendChild(li);
}
I’m going to add an event listener to the form that watches for a submit event – which will be any time you press enter on the form. The e.preventDefault()
will prevent the form from the default submit action, which we don’t want, since we’re not sending any data to a server.
Instead, the form will submit the value of the input
. We’re going to call the liMaker()
function, which will create the item with the text of the input
value and append it to the DOM. Finally, we’ll set the input
value to an empty string so you don’t have to erase the last item entered manually.
form.addEventListener('submit', function (e) {
e.preventDefault();
liMaker(input.value);
input.value = "";
});
Now with paltry few lines of code, we have a little app that adds to-do items to a list.
Since we’re not saving the items anywhere, when you close or refresh the browser, the items will be gone. The final step is to integrate it into local storage so that the data persists.
Integrating local storage
Now we’re going to add a few more bits of functionality to the app. First, every time the form is submitted, the input
value should be added to the localStorage
as well as appear on the front end. We’ll also want to loop through all the existing local storage items and display them at the top of the list. Last, we want the “Clear All” button to remove all items from local storage as well as the front end.
Let’s create an empty array to start, and create a localStorage
key called “items”. Now, localStorage
only supports strings as values, and want to store our to-dos in an array.
We can get around this by using JSON.stringify()
to convert a data array to a string. We’ll use JSON.parse()
to convert the contents of localStorage
back into something we can work with later in the data
variable. Put this code below all the constant declarations we set earlier.
// other constant declarations here
...
let itemsArray = [];
localStorage.setItem('items', JSON.stringify(itemsArray));
const data = JSON.parse(localStorage.getItem('items'));
In the form event listener, let’s push any new input
value into the array, then set the localStorage
to the new, updated value.
// form event listener here
...
e.preventDefault();
itemsArray.push(input.value);
localStorage.setItem('items', JSON.stringify(itemsArray));
We’re going to loop through everything in our data
variable above, which contains all the existing localStorage
data in a form JavaScript can understand and work with, and we’ll run the liMaker()
again. This will display all existing stored information on the front end every time we open the app.
data.forEach(item => {
liMaker(item);
});
Last, we’ll add a click event to the button that will clear all data from localStorage
, as well as removing every child node from the ul
.
button.addEventListener('click', function () {
localStorage.clear();
while (ul.firstChild) {
ul.removeChild(ul.firstChild);
}
});
If all went well, everything will save to storage as well as appear on the front end, which you can check by testing localStorage
in the console.
Storage {items: "["Welcome","to","the","Thunderdome"]", length: 1}
There’s one final problem: after closing the browser or reloading the page, all the existing information in localStorage
is gone, and nothing remains on the front end. Why?
Our itemsArray
is being reset to an empty array every time the script runs. We could fix this by making a conditional statement that checks if localStorage
already exists, such as in the below example.
let items;
if (localStorage.getItem('items')) {
items = JSON.parse(localStorage.getItem('items'));
} else {
items = [];
}
A little more concise would be to use a ternary operator to do the same thing.
let itemsArray = localStorage.getItem('items') ? JSON.parse(localStorage.getItem('items')) : [];
With that, our app is complete! Now when you enter in some information and refresh or close the browser window, the data will persist until you manually clear the data in Developer Tools (under Application -> Storage) or by running the localStorage.clear()
command. Here is the full JavaScript code.
const form = document.querySelector('form');
const ul = document.querySelector('ul');
const button = document.querySelector('button');
const input = document.getElementById('item');
let itemsArray = localStorage.getItem('items') ? JSON.parse(localStorage.getItem('items')) : [];
localStorage.setItem('items', JSON.stringify(itemsArray));
const data = JSON.parse(localStorage.getItem('items'));
const liMaker = (text) => {
const li = document.createElement('li');
li.textContent = text;
ul.appendChild(li);
}
form.addEventListener('submit', function (e) {
e.preventDefault();
itemsArray.push(input.value);
localStorage.setItem('items', JSON.stringify(itemsArray));
liMaker(input.value);
input.value = "";
});
data.forEach(item => {
liMaker(item);
});
button.addEventListener('click', function () {
localStorage.clear();
while (ul.firstChild) {
ul.removeChild(ul.firstChild);
}
});
Here is the demo and source code once again.
Conclusion
In this tutorial, we learned how to make a simple to-do based application that can potentially be used to keep quick notes as a new tab page by using HTML5 web storage. I hope you have a better understanding of local storage and how to integrate it into a simple app now! Please share this article if you found it helpful so that others can benefit as well.
Newsletter
Get updated when I create new content.
Unsubscribe whenever. Never any spam.
Dear Tania
That was very useful information
Yours Sincerely
helpful
Thanks, this is great.
Why it's not working in Internet explorer
good Work .. very usefull information Thnx
thanks Tania,
is it possible to get the local storage of another person ?
let assume that I save some data in my local storage which is my online status,
I want to let another person who serve your site to get this data and knows that I'm online. I don't want this to go through database. is there anyway to do that? I hope you got what I mean
test
Que Bela Porcaria!
Hey love your articles, i'm actually studying this unit right now ???????????????? really helped me alot.
quick suggestion: could u use
//code
form.reset();
instead of
// code
input.value = "";
Thanks
test
Ufff thank you. I really was searching for this.
+10
Hi Tania, your post is really very helpful for me thanks for making such a nice post.
Thank You
How would you get every saved data to get a uniqe id. For example, first data you create and store in localstorages, gets the id1, next gets id2 and so on.
d
How about a tutorial on making a comment section like this one, where no login whatsoever is required. I am currently looking for something like this.
This works great. Thank you!
Wonderful example. If localStorage works this great on just about every browser. Can the same principle work on a serverless database? Is there any NoSQL database or open source project that would handle this type of approach for handling larger amounts of data and keeping it always available for both the user and website or app administrator? Would firebase or dynamodb fall into this category?
some code please
vl
Great Article!Thank a lot…Gave a clear idea about localStorage.
Hi Tania,
I am following your "How to use local storage with Javascript" tutorial. I am having trouble with the css. I am using your link to Primitive, " <link rel="stylesheet" href="https://taniarascia.github.io/primitive/css/main.min.css"> and it returns
"Failed to load resource: the server responded with a status of 404 ()".
What should I use for the css link? Am I making a mistake using this link to begin with?
Thank you for your help, Roger. I like your tutorials, I never cared for the foo, bar and baz business either.
Roger, you want to use this URI: https://taniarascia.github.io/primitive/css/main.css
nkn
thanks a useful article
so helpfull really thanx keep posting such posts
Hey,
This is really a good article. I am working as a Web developer. I need some more deep examples for the same.
I am currently on month 1 at the Nashville Software School. It's been tough. I am at the point where I know what I'm looking at but still figuring out how to put it all together. Your tutorials are so perfect and help me. Thanks for taking the time to do this. I am going to go though all of your tutorials. Thanks so much!
You're welcome! Glad I'm able to help you out.
another student from Nashville Software School, sending appreciation. I am (probably) one class behind Mike ^ and feel overwhelmed but not discouraged.
Good Morning Madam!
I am new for the javascript please tell me how to learn javascript step by step….
Its simple…….
lear basics of HTML = Element, Attributes, heading, Paragraphs, styles, formatting, Quotations, Comments, Colors, CSS, Links, Images, Tables, Lists, Blocks, Classes, HTML JavaScript
Then basic CSS = Syntanx, Colors, Background, Border, Margin, padding, Height-Width, Box Model, Text, Font, Icon, Links, List, Tables, Display, Positions, Overflow, Float
The Last JavaScript = Variables, Operators, Arithmetic, Assignment, Data type, Functions, Objects, Events, Strings, Strings Methods,Numbers, Number Methods, Array, Array Methods, Array Sort, Array Iteration, And All The Loops(for, while, dowhile, switch, )
Oh~!! Thank U !! I solved the problem.
wow, you helped me understand local storage
There is a need to add to button.addEventListener the following string
itemsArray = [];
If it's not it won't be working properly
If a user wants to clear storage and add a new item the localStorage will have removed items as well
Very good explanation. Thank you, Tania!
You're welcome.
Thank You Tania!!!
how can i let websites use spare storage space on my computer.
Hello, I'm working with LS and your example helps me a lot, however, I do want to send data to server…how can I adjust these code for my purpose?
thanks in advanced!
ddf
Obrigado pelo tutorial, me ajudou muito!
hi sooper
Hei Tania, can you show me how to clear the list one by one?
localStorage.clear; doesn’t work on button click as intended to be. It keeps the data in session until you hard refresh the page. When you press “clear” it removes the data temporarily, but if you enter a new item right after clear, it built the same storage and adds a new item to it. It is basically restoring.
I am using windows 7, xampp, brackets.io and when I declare using const keyword, I keep getting error:
Uncaught SyntaxError: Identifier ‘form’ has already been declared
If I switch back to var, seems to work. I am newbie.
You can’t change the value of const.
how to send that data to mysql data base using php?
very nice tutorial .. thanx
Hi,
wouild it be possible to add Icons to the local storage?
Hi Roland. Local storage is text only.
Thanks for this article Tania. Really help me a lot.
Great article Tania 🙂
Just one mark, add to input tag “required” to prevent adding empty item to array.
Thanks! Good point.
It was very complete guide for using localStorage.
Thank you for sharing this useful article
Since I’m new to web development this was very useful Thanks.
I just wanna point that you forgot to clear the itemsArray when you press Clear. So if you do these steps: `insert an item -> press clear -> insert another one -> reload the page` it shows the last items that were stored in the array.
Also you can submit empty inputs. I wrapped the form submit event with a if condition.
Thanks for this tutorial!
LocalStorage was daunting at first. And I had to read this article a few times while applying it to my app. Thank for providing this.
Local storage has been around since 2011. It has been documented in depth throughout the web (https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API).
The article is way too late and shouldn’t be sent to me in a Collective newsletter.
Thumbs up for the effort though.
Not everyone has been programming since 2011 though! Even though it’s well-documented, I still think this is a great introductory tutorial.
@Stanimir Genov – it’s ironic that you’re complaining about the date this tutorial was created, yet you reference Mozilla’s article, which was updated 01/18/2018. Thumbs down for the ignorance though.
It’s new to me.. thanks
As a beginner in JavaScript, I really love how detailed your instructions are, loving it, keep it up!!
Thanks, I will!
Good tut. Btw.. you might want to add a warning about security.
If I had a dollar for every site that stored inappropriate data in localstorage… well… I’d have at least 10 bucks.
Good point, I’ll add a note in.
Hi,
Great tutorial on localStorage. I am learning a lot from your post. Howdy from LA – I grew up in Chicago (northwest side).
I cannot seem to get your code to work. I replicated your code word for word in the html, js, and css – just can't get it to work properly in any of my browsers.
I keep getting the following error from Dreamweaver when I look at the js:
<There is a syntax error on line 6 of scripts.js Code hinting may not work until you fix this error>
I am not sure how to fix?
Thank you very much for your help, and thank you again for your posting!
You're going to have to look at line 6.