The localStorage mechanism provides a type of web storage object that lets you store and retrieve data in the browser. You can store and access data without expiration; the data will be available even after a visitor closes your site.

You’ll normally access localStorage using JavaScript. With a small amount of code, you can build a sample project, like a score counter. This will show how you can store and access persistent data using only client-side code.

What Is localStorage in JavaScript?

The localStorage object is part of the web storage API that most web browsers support. You can store data as key-value pairs using localStorage. The unique keys and values should be in the UTF-16 DOM String format.

If you want to store objects or arrays, you'll have to convert them to strings using the JSON.stringify() method. You can store up to 5MB of data in localStorage. Also, all windows with the same origin can share that site's localStorage data.

A browser will not delete this data even when a user closes it. It will be available to the website that created it during any future session. However, you shouldn't use localStorage for sensitive data since other scripts running on the same page can access it.

localStorage vs. sessionStorage

The localStorage and sessionStorage objects are part of the Web Storage API that stores key-value pairs locally. All modern browsers support them both. With localStorage, the data does not expire even after a user closes their browser. This differs from sessionStorage which clears data when the page session ends. A page session ends when you close a tab or window.

The code used in this project is available in a GitHub repository and is free for you to use under the MIT license. If you want to have a look at a live version of the score counter project, you can check out the live demo.

How Does localStorage Work?

You can access the localStorage functionality through the Window.localStorage property. This property provides several methods like setItem(), getItem(), and removeItem(). You can use these to store, read, and delete key/value pairs.

How to Store Data in localStorage

You can store data in localStorage using the setItem() method. This method accepts two arguments, the key, and the corresponding value.

        window.localStorage.setItem('Python', 'Guido van Rossum');
    

Here, Python is the key and Guido van Rossum is the value. If you want to store an array or an object, you will have to convert it to a string. You can convert an array or an object into a string using the JSON.stringify() method.

        window.localStorage.setItem('Python', 'Guido van Rossum');
 
const student = {
    name: "Yuvraj",
    marks: 85,
    subject: "Machine Learning"
}
 
const scores = [76, 77, 34, 67, 88];
window.localStorage.setItem('result', JSON.stringify(student));
window.localStorage.setItem('marks', JSON.stringify(scores));

How to Read Data From localStorage

You can read data from localStorage using the getItem() method. This method accepts the key as a parameter and returns the value as a string.

        let data1 = window.localStorage.getItem('Python');
let data2 = window.localStorage.getItem('result');
 
console.log(data1);
console.log(data2);

This produces the following output:

        Guido van Rossum
{"name":"Yuvraj","marks":85,"subject":"Machine Learning"}

If you want to convert the result from a string to an object, you should use the JSON.parse() method.

        let data2 = JSON.parse(window.localStorage.getItem('result'));
console.log(data2);

How to Delete localStorage Sessions

You can delete localStorage sessions using the removeItem() method. You need to pass the key as a parameter to this method to delete the key-value pair. If the key exists, the method will delete the key-value pair and if the key does not exist, the method will do nothing.

        window.localStorage.removeItem('Python');
window.localStorage.removeItem('C++');

How to Clear All Items in localStorage

You can clear all items in local storage using the clear() method. You don't need to pass any parameter to this method.

        window.localStorage.clear();
    

How to Find the Length of localStorage

You can find the length of localStorage using the localStorage.length property.

        let len = localStorage.length;
console.log(len);

How to Get the Key at a Given Position

You can get the key on a given position using the key() method. This method accepts the index as a parameter.

        let d = localStorage.key(1);
console.log(d);

The key() method is primarily used to loop through all the items in localStorage.

How to Loop Through All the Items in localStorage

You can iterate over all the items in localStorage using a for loop.

        for (let i = 0; i < localStorage.length; i++){
    let key = localStorage.key(i);
    let value = localStorage.getItem(key);
    console.log(key, value);
}

The key() method accepts the index as an argument and returns the corresponding key. The getItem() method accepts the key as an argument and returns the corresponding value. Lastly, the console.log() method prints the key-value pair.

Simple JavaScript Project Based on localStorage

With an understanding of its basic methods, you can develop a simple JavaScript project based on localStorage. In this project, you'll create a score counter app that will increase and decrease the score count according to a button click. Also, you'll implement functionality to clear all items in localStorage.

Create an index.html and script.js file in a new folder and open the files in your favorite code editor. Use the following HTML code to create an interface for the score counter app:

        <!DOCTYPE html>
<html>
<body>
    <h1>localStorage in JavaScript</h1>
    <button onclick="increaseCounter()" type="button">Increase Score</button>
    <button onclick="decreaseCounter()" type="button">Decrease Score</button>
    <button onclick="clearCounter()" type="button">Clear localStorage</button>
    <p>Score:</p>
    <p id="score"></p>
    <p>Click on the "Increase Score" button to increase the score count</p>
    <p>Click on the "Decrease Score" button to decrease the score count</p>
    <p>Click on the "Clear localStorage" button to clear the localStorage</p>
    <p>
        You can close the browser tab (or window), and try again.
        You'll see that the data still persists and is not lost even after closing
       the browser.
    </p>
    <script src="script.js"> </script>
</body>
</html>

This page contains three buttons: Increase Score, Decrease Score, and Clear localStorage. These buttons call the increaseCounter(), decreaseCounter(), and clearCounter() functions respectively. Use the following code to add functionality to the score counter app using JavaScript.

        function increaseCounter() {
    var count = Number(window.localStorage.getItem("count"));
    count += 1;
    window.localStorage.setItem("count", count);
    document.getElementById("score").innerHTML = count;
}

The increaseCounter() function retrieves the count using the getItem() method. It converts the result into a Number, since getItem() returns a string, and stores it in the count variable.

The first time you click on the Increase Score button will be before any call to setItem(). Your browser will not find the count key in localStorage, so it will return a null value. Since the Number() function returns 0 for a null input, it doesn't need any special case handling. The code can safely increase the count value before storing it and updating the document to display the new value.

        function decreaseCounter() {
    var count = Number(window.localStorage.getItem("count"));
    count -= 1;
    window.localStorage.setItem("count", count);
    document.getElementById("score").innerHTML = count;
}

The decreaseCounter() function retrieves and checks the data just like increaseCounter() does. It decrements the count variable by 1, which defaults to 0.

        function clearCounter() {
    window.localStorage.clear();
    document.getElementById("score").innerHTML = "";
}

Last, the clearCounter() function deletes all the data from localStorage using the clear() method.

Do More With localStorage

The localStorage object has several methods including setItem(), getItem(), removeItem(), and clear(). While localStorage is easy to use, it is not safe to store sensitive information. But it's a good choice to develop projects that don't require much storage and don't involve any sensitive information.

Want to build another localStorage based JavaScript project? Here's a basic to-do list app that you can develop using HTML, CSS, and JavaScript.