The Developer’s Guide to localStorage

Learn the ins and outs of localStorage, the persistent Storage object that you can use for storing data in the browser.

Published Categorized as JavaScript

Local storage (localStorage) is both a Web API and a Storage object that lets developers store information in the form of key-value pairs in the user’s web browser.

To access localStorage, open your browser’s developer tools, navigate to the “Application” tab, and look for “Local Storage.” Although there are many uses for such a storage interface, localStorage is typically used for storing data that needs to persist across user sessions, windows, and tabs.

That’s the main benefit of localStorage — the data items stored in it are shared between tabs, windows, and user sessions, which makes it a fantastic alternative to first-party cookies.

Unlike sessionStorage, which is limited to the current session and which gets cleared as soon as the user closes the tab or window, localStorage holds its key-value pairs from one session to another and is only cleared when the user deletes their browser’s cache.

How to Save an Item in Local Storage

To save information in the browser’s localStorage, you should use the setItem() method. For example, the statement below saves the key-value pair username/john-doe to localStorage:

localStorage.setItem("username", "john-doe");

Where username is the key and john-doe, the value.

Local storage only supports strings as values. When you store data in the browser’s local storage using the localStorage.setItem() method, you have to provide the data as a string. (Although there are ways to store objects and arrays in it; read on and we’ll get to them soon.)

How to Read an Item From Local Storage

To read information from the browser’s localStorage, you need to use use the getItem() method:

localStorage.getItem("username");
console.log(item); // Logs "john-doe"

Where username is the key of the item you want to read.

If you try to retrieve a non-existent item, the localStorage.getItem() method will return null. Here’s an example:

let item = localStorage.getItem("keyDoesNotExist");
console.log(item); // Logs "null"

How to Check If a Local Storage Item Exists

Every so often, your application’s will need to check if an item exists in the localStorage so that it can branch out its logic and handle the two cases differently. Here’s an example:

// Declare function
function checkItem(itemKey) {
    let item = localStorage.getItem(itemKey);
    if (item) {
        // Do this if the item exists
        console.log("The item exists");
    } else {
        // Do this if the item doesn't exist
        console.log("The item doesn't exist");
    }
}

// Call function
checkItem("yourItemKey");

How to Save an Object to Local Storage

Sometimes, you’ll need to store a data type other than a string in the browser’s localStorage, like an object or an array. To do this, you will need to convert it to a string first. You do this by using JSON.stringify().

Here’s how this works:

var user = {"firstName": "John", "lastName": "Doe"};
localStorage.setItem("user", JSON.stringify(user));

This will convert your object or array into a JSON string. If you need to parse that JSON string back, you can use the JSON.parse() method like so:

JSON.parse(localStorage.getItem("user"));

In Summary

Thanks for reading this far! I hope this guide helped you understand how localStorage works, and how you can set and get data items to and from this Storage object for your application’s needs.

If you have any questions, or would like to share tips and tricks of your own with the rest of this post’s readers, leave a reply below.

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

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