LearnHow to Store Data in LocalStorage in JavaScript


Matt West
writes on November 25, 2022

The LocalStorage API gives front-end web developers access to a simple key-value datastore that can be used to save data on a user’s computer.

Saving data on the client side can help speed up the performance of your web applications as it can reduce the number of database queries needed on the server. This frees up valuable server resources and can potentially even lead to reduced infrastructure costs.

Before the introduction of LocalStorage, developers that wanted to store data on the client would need to use browser cookies. While this approach did work, it had some problems. The first issue is that a cookie can only store 4,096 bytes of data, which isn’t really all that much.

Another issue is that cookies are sent up to the server with every HTTP request that is made by the client. This increases the size of requests, leading to higher bandwidth usage and slower request times.

In this guide, you’ll learn how to store data in LocalStorage in JavaScript. Let’s get started.

Does Your Browser Support the LocalStorage API?

LocalStorage is a new technology. It’s important that we test for browser support and consider fallbacks for browsers that do not support the API. Testing for LocalStorage support is very straightforward.

All you need to do is create a simple “if” statement that contains the localStorage interface as the condition. Note the lowercase ‘l’ in localStorage.

The JavaScript code below shows how you could test to see if a browser supports the LocalStorage API.

if (localStorage) {
  // LocalStorage is supported!
} else {
  // No support. Use a fallback such as browser cookies or store on the server.

If the browser does not support LocalStorage, you could fall back to using browser cookies or just send the data to be stored on the server.

Now that you understand how to check for support for LocalStorage, let’s take a look at how to store data in LocalStorage in JavaScript.

Related Reading: What Is JavaScript?

How to Store Data in LocalStorage in JavaScript

To store data in LocalStorage, you use the setItem() function. This function takes two parameters, the item key, and a value.

localStorage.setItem('name', 'Matt West');

Note: There are multiple ways to interact with the localStorage interface. In this blog post, I use the functions outlined in the official specification, but you can also treat the localStorage interface like a JavaScript object or array. The examples below will all store data.

// Functions
localStorage.setItem('name', 'Matt West');

// Object
localStorage.name = 'Matt West';

// Array
localStorage['name'] = 'Matt West';

For the remainder of this blog post, I will be using functions to interact with the localStorage interface.

Let’s take a look at a simple use of LocalStorage on a website. The code below is markup for a contact form. When the user submits the form, we are going to save their name so that we can use it later to show them a personalized message.

<form id="contactForm" action="contact.php" method="POST">
  <div class="field">
    <label for="name">Name</label>
    <input type="text" name="name" id="name">
  <div class="field">
    <label for="email">Email</label>
    <input type="email" name="email" id="email">
  <div class="field">
    <label for="message">Message</label>
    <textarea name="message" id="message"></textarea>
  <div class="field">
    <input type="submit" value="send">

The JavaScript code below shows how you could intercept the form submission and save the user’s name.

window.onload = function() {

  // Check for LocalStorage support.
  if (localStorage) {

    // Add an event listener for form submissions
    document.getElementById('contactForm').addEventListener('submit', function() {
      // Get the value of the name field.
      var name = document.getElementById('name').value;

      // Save the name in localStorage.
      localStorage.setItem('name', name);



Now that you know how to save data to the datastore, let’s take a look at how to get it back out again.

How to Retrieve Data From LocalStorage

To retrieve data, you use the getItem() function. This takes a single parameter; the key that you used when storing data.

var name = localStorage.getItem('name');

Building on our previous contact form example, in the code below, we retrieve the user’s name from the datastore and then update an element on the page with the text Hello {name}!.

window.onload = function() {

  // Retrieve the users name.
  var name = localStorage.getItem('name');

  if (name != "undefined" || name != "null") {
    document.getElementById('welcomeMessage').innerHTML = "Hello " + name + "!";
  } else
    document.getElementById('welcomeMessage').innerHTML = "Hello!";

The if statement is used to make sure there is a name stored in the database. If we didn’t do this, our program might say Hello undefined!.

If you attempt to access data that does not exist, the localStorage interface will return either null or undefined depending on how you tried to access the data (see the note earlier in this post).

How to Remove Data From LocalStorage

To remove an item from the datastore you use the removeItem() function. This function takes the key of the item that you wish to delete.


Clearing the LocalStorage Datastore

If you want to delete all of the data in the datastore you can use the clear() function.


Retrieving Keys in LocalStorage

The localStorage interface also includes a function called key() that can be used to retrieve the key of a data item using the index (numerical position) of the item in the datastore. Admittedly, you will probably not be using this function very often but it is useful to know that it exists.

The JavaScript code below shows how you might use this function to output the keys for each of the items in the datastore.

for (var i = 0; i < localStorage.length; i++) {

Note the use of localStorage.length in this example. The length property tells you how many items are in the datastore.

Sandboxing and Storage Limits

The data that you add to the LocalStorage datastore is sandboxed to your website’s domain name. This means that your web application can’t see the data stored by any other applications and those applications cannot see the data stored by yours. This is an important security measure.

Sub-domains (i.e. a.example.com, b.example.com, c.example.com) are treated as separate domains and are therefore given their own datastore.

There is a limit on how much data you can put in LocalStorage. This limit is set by browser vendors and therefore varies between browsers.

To be safe, you should assume that your web application has only 2.5mb of storage space. This should be more than enough space as LocalStorage is only designed to hold basic key-value data. If you find yourself needing more space, you might want to reconsider whether LocalStorage is the best storage technology for your application.

How to Use SessionStorage

Data stored in LocalStorage is persistent. This means that if you store some data, close your browser and then open up your application again, all of the data will still be retrievable.

However, you may only want to store some data for the duration of a user session. In this case, you can use the sessionStorage interface. This has all of the same functions that localStorage does but the data you save will automatically be wiped when the user closes the browser tab.

// Storing Data
sessionStorage.setItem('name', 'Matt West');

// Retrieving Data
var name = sessionStorage.getItem('name');

// Deleting Data

// Retrieving an Item Key

// Clearing the Datastore

Thoughts on the LocalStorage API

The LocalStorage API allows developers to make considerable advances in the performance of their web applications. Looking past this initial advantage, LocalStorage also provides a datastore for offline applications (assuming that a technology like AppCache is being used to make the other application resources available).

I am especially interested in the potential applications that LocalStorage has for HTML5 mobile applications. Mobile devices are much more likely to be without an internet connection and therefore without access to traditional server-based datastores.

Are you using LocalStorage in any interesting ways in your projects? Let us know in the comments below.

Improve Your Programming Skills With Treehouse

Ready to take your programming skills to the next level? Treehouse offers Techdegrees and courses to help you do just that. Our faculty of tech professionals will guide you through mastering the fundamentals of coding. Try our courses today by signing up for a free trial of Treehouse!

Useful Links


Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started

15 Responses to “How to Store Data in LocalStorage in JavaScript”

  1. Good tutorials, I wanted to know. When I save an image to the local storage, I will have an url. When I query the url I get the image. My questionis how to keep the image in local storage when he image from my local the system is deleted.

  2. Nice tutorial about the usages of localStorage, sessionStorage and cookies and their limitations.

  3. how to maintain the large amount of data by using localStroage/sessionStroage

    i am getting this how to resolve it.

    Failed to execute ‘setItem’ on ‘Storage’: Setting the value of ItemsObject’ exceeded the quota.

  4. How Can i access the length of a localStorage array.

    I tried $LocalStorage.myarray.length but it does’nt work….

  5. Hi,

    Is there something missing or extra that I need to add to this code?
    I copied it in whole and I get the message below.

    Your file was not found.
    It may have been moved or deleted

  6. In your section on ‘Retrieving Data from LocalStorage,’

    if (name != “undefined” || name != “null”)

    should be

    if (name != “undefined” && name != “null”)

  7. santosh on January 6, 2016 at 1:14 am said:

    how to store values for all browsing domains like global in browser with javascript

  8. Hi!

    can you gave me an example on how use localstorage in simple add/edit/delete?


  9. Hi,
    I have used localStorage in my application. I have hosted application in different environment like DEV, TEST and QC. If I open all different environment links in same browser’s different tabs, how could be stored data into localStorage?


  10. joaoN1x on August 23, 2013 at 9:44 am said:

    I use a lot localStorage as it is the most compatible, even with limits on size usage on some browsers

    i created a simple and efficient way of dealing with
    localStorage as database with all the whistles add/remove/update easy
    and quick

    you can check in github https://github.com/joaoN1x/DBosta.js

  11. Miss Sher on July 8, 2013 at 9:48 am said:

    Hi, may I know how we could retrieve all items that were added to local storage in the user’s browser? currently I can retrieve the last item added using getItem()

  12. lammy on May 8, 2013 at 11:24 am said:

    If I redirect immediately to other sites, the localstorage will be not saved in Browser. What is the problem?

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop