DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for JavaScript Local Storage Explained!
Boateng Dickson
Boateng Dickson

Posted on • Updated on

JavaScript Local Storage Explained!

In the early days of the internet, you needed a server to store data. But nowadays, through LocalStorage, you can store data on browsers and applications without communicating with a back-end server.

In this article, you will learn about the theoretical and practical applications of LocalStorage in JavaScript.

Let's talk about web storage

Before we hop into the real deal, let's look at the definition of web storage. Web storage is one of the great features of HTML5 that allows web applications to store data locally within a user's browser.

The two most common forms of web storage are LocalStorage and Session Storage. The key difference between these two forms of web storage is that data saved in LocalStorage never leaves the browser and remains there until you explicitly remove it. In contrast, data stored in Session Storage is removed once a browser tab/window is closed.

What is Local Storage?

As mentioned earlier, LocalStorage is a form of web storage provided by the browser that allows web applications to store data locally within a user's browser with no expiration date. Here, stored data will remain available even when you close a browser tab/window.

Note that the data stored in LocalStorage is only preserved on a user's browser on the device they used to access a site. Hence, users cannot access the stored data if they revisit the same site later with a different browser or on another device.

LocalStorage Use Cases

The following presents some everyday use cases of LocalStorage.

1. Store Partially Submitted Form Data

If a user fills out a long form online, LocalStorage can be a helpful resource for storing user inputs. In that case, even if the internet gets disconnected between filling out the form and submitting it, users won't lose their inputs and can continue from where they left off.

2. Caching

Caching refers to storing data such as login details on a user's device so that future requests for that data can be served faster. You can use LocalStorage to cache a whole website so that users can still have access to the site even when they are offline.

3. Database for basic applications

As mentioned earlier, data storage was initially only possible by communicating with a database through the backend. But now, with LocalStorage, you can store data on the frontend without needing a database. Hence LocalStorage can sometimes serve as a "little" database for basic applications.

How to Access LocalStorage

Accessing LocalStorage is pretty simple and takes only a few steps:

  1. Go to any website or web application and open the browser console by pressing F12 on the keyboard.
  2. Next, click on the Application tab, and in the menu on the left, you will see LocalStorage under the Storage tab as shown below.

  1. Click on the LocalStorage dropdown and further click on a/the dropdown item.

As can be seen, there are two columns, key, and value. This is where LocalStorage stores every data you save to it.

How to Use Local Storage

You can use following methods to manage data in LocalStorage.

Method Description
setItem() To store data in LocalStorage.
getItem() To get or retrieve the data from LocalStorage
removeItem() To delete data from LocalStorage using a key
key() To retrieve data from LocalStorage at a specified index

setItem( )

This method is used to store data in LocalStorage. It accepts a key as its first argument and then a value as the second argument.

Let's add data to LocalStorage using the following.

localStorage.setItem("name", "Mandy");
// Here, `name` is the key and `Mandy` is the value
Enter fullscreen mode Exit fullscreen mode

As mentioned earlier, LocalStorage stores data as strings, so if you want to save data such as objects and arrays, you need to convert them to strings using the JSON.stringify() method.

Let's see how this works!

//Storing objects in LocalStorage
const user = {
  name: "Mandy",
  age: 23,
};

localStorage.setItem("user-info", JSON.stringify(user));

//Storing arrays/lists in LocalStorage
const names = ["John", "Jake", "Vanessa"];
localStorage.setItem("names", JSON.stringify(names));
Enter fullscreen mode Exit fullscreen mode

getItem()

Use the getItem() method to retrieve data from LocalStorage. This method accepts a single parameter, which is the key used when saving data.

For example, to retrieve data such as the above user object, you will use the following statement:

localStorage.getItem("user-info");
Enter fullscreen mode Exit fullscreen mode

The above code will return a JSON string as shown below:

"{name:"Mandy", age:"23"}"
Enter fullscreen mode Exit fullscreen mode

You should then convert it to an object using the JSON.parse() method.

JSON.parse(localStorage.getItem('user-info'));
Enter fullscreen mode Exit fullscreen mode

removeItem()

Use the removeItem() method to remove data from LocalStorage. This method accepts a key as a parameter.

For example, you will use the following statement to delete the user object from LocalStorage.

localStorage.removeItem("user-info");
Enter fullscreen mode Exit fullscreen mode

key()

Use key(index) method to retrieve data from LocalStorage, where index represents the nth data you want to retrieve.

localStorage.key(2);
Enter fullscreen mode Exit fullscreen mode

clear()

Use the clear() method to clear out or remove all data from LocalStorage at a particular instance.

localStorage.clear()  
Enter fullscreen mode Exit fullscreen mode

Project

Now that you've learnt about the main methods used to manage data in LocalStorage, let’s get our hands dirty by creating a web application where users can:

  • Save data to LocalStorage
  • Retrieve the data
  • Remove/Delete the data using a key
  • And also clear out all data from LocalStorage.

Let's start by creating a new folder and open it in a code editor. Next, create three files, index.html , style.css and main.js.

Let’s Code!

The index.html file will contain the HTML markup for the web application. The HTML code comprises a form having various input fields with buttons.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Local Storage</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div id="form">
      <form id="userForm">
        <h1>LocalStorage Application</h1>
        <label for="userName">User</label>
        <input
          type="text"
          id="userName"
          placeholder="Enter user name"
          required
          autofocus
        /><br />
        <label for="age">Age</label>
        <input
          type="number"
          id="age"
          placeholder="Enter user age"
          required
        /><br />
        <label for="key">Key</label>
        <input type="text" id="key" placeholder="Enter key" required /><br />
        <button type="submit">Save user</button>
      </form>
      <br />
      <label for="key">Enter Key to retrieve user</label>
      <input
        type="text"
        id="retrieveKey"
        placeholder="Enter key to access user"
        required
      /><br />
      <button id="retrieveButton">Retrieve user</button>
      <br />
      <div id="userData"></div>
      <br />
      <label for="removeKey">Enter Key to delete user</label>
      <input
        type="text"
        id="removeKey"
        placeholder="removeKey"
        required
      /><br />
      <button id="removeButton">Delete user</button>
      <br />
      <button id="clearButton">Delete all users</button>
    </div>
    <script type="text/javascript" src="main.js"></script>
  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

Here's the CSS code.

/* base styles  */
html {
  font-size: 67.5%;
}
body {
  font-size: 1.6rem;
  padding: 0;
  margin: 0;
}

/* form   */
#form {
  margin-left: 2rem;
}

Enter fullscreen mode Exit fullscreen mode

Here’s the main.js file containing all the functions to store, retrieve, and delete data from LocalStorage.

//store user data in the localStorage
function store() {
  var userName = document.getElementById("userName").value;
  var age = document.getElementById("age").value;
  var key = document.getElementById("key").value;

  const user = {
    userName,
    age,
  };

  //convert user object to string and save it
  localStorage.setItem(key, JSON.stringify(user));
}

//retrieve user data from localStorage
function retrieveUserData() {
  let key = document.getElementById("retrieveKey").value;
  console.log("retrive records");
  let userData = localStorage.getItem(key); //searches for the key in localStorage
  let paragraph = document.createElement("p");
  let info = document.createTextNode(userData);
  paragraph.appendChild(info);
  let element = document.getElementById("userData");
  element.appendChild(paragraph);
  retrieveKey.value = "";
}

//delete user data from localStorage
function removeUserData() {
  var removeKey = document.getElementById("removeKey").value;
  localStorage.removeItem(removeKey);
  removeKey.value = "";
}

//delete all user data from localStorage
function deleteAllUserData() {
  localStorage.clear();
}

//ensures the page is fully loaded before functions can be executed.
window.onload = function () {
  document.getElementById("userForm").onsubmit = store;
  document.getElementById("clearButton").onclick = deleteAllUserData;
  document.getElementById("removeButton").onclick = removeUserData;
  document.getElementById("retrieveButton").onclick = retrieveUserData;
};
Enter fullscreen mode Exit fullscreen mode

Results

The following video shows how the final result of the project works:

Some Essential Points About LocalStorage

  • Local storage has no data protection and it is therefore not secure to store sensitive data as they can be accessed by anyone.
  • Local storage can only store a maximum of 5MB of data on the browser.

Conclusion

I encourage you to practice and experiment with LocalStorage by using it in your applications. Get used to saving, retrieving, and removing data from it.

Thanks for reading!

I hope this has been a worthwhile read. Kindly share this article and follow me on Twitter @dboatengx for updates on future posts.

Cheers!

Top comments (15)

Collapse
 
cicirello profile image
Vincent A. Cicirello

I use local storage for the site search page for my personal website to cache the search index. My site is a static website hosted on GitHub Pages. So without a backend, and without using some 3rd party service, search is run entirely in browser. Obviously can't feasibly do this for a very large site. But index for my site is just under 800 KB.

When using local storage for caching, you do need some mechanism to know when to use cached version and when to make a fresh request.

Collapse
 
kolja profile image
Kolja

RepoLink, please πŸ˜ƒ

Collapse
 
cicirello profile image
Vincent A. Cicirello

The GitHub repo is: github.com/cicirello/cicirello.git...

The site itself is at: cicirello.org/

Collapse
 
alonedatascientist profile image
alonedatascientist

Good article! Very thorough.

Local Storage is super useful when you are in that intermediate sort of middle with learning and making projects. Maybe you need to save some data but perhaps you aren't trying to learn a database yet. Or maybe some simple prototyping. As long as you use it knowing its not secure and that eventually you'll have to give up the training wheels and head for a more robust data store I see it as a nice solution.

Collapse
 
rahulranjanme profile image
Rahul Ranjan

We use localStorage and its "storage" eventListener to share data from one tab to another.

Collapse
 
fruntend profile image
fruntend

Π‘ongratulations πŸ₯³! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 🫰

Collapse
 
yongchanghe profile image
Yongchang He

Thank you for sharing this!

Collapse
 
andrewbaisden profile image
Andrew Baisden

Thats a super explanation.

Collapse
 
olsard profile image
olsard

Thank you

Collapse
 
annie profile image
Annie

Hello, I love your article. Can I reprint and translate your article? I will include a link to the article.

Collapse
 
dboatengx profile image
Boateng Dickson Author

Hey, that's not a problem.

Collapse
 
dhruvjoshi9 profile image
Dhruv Joshi

was looking for something like this!!! thanks man!

Collapse
 
kosoko_daniel profile image
Daniel

Thank you

Collapse
 
kosoko_daniel profile image
Daniel

Thank you

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.