JavaScript Local Storage

JavaScript Local Storage

In the world of modern web development, keeping data close to the user is a big win. One way JavaScript makes this possible is through the Web Storage API, specifically Local Storage. This feature allows developers to store data in the user’s browser without needing a server or database. Local Storage is incredibly useful when you want to remember information between browser sessions — like keeping a user’s theme preference, remembering a selected tab, or even storing progress in a small game.

Unlike session storage, which disappears when the browser is closed, Local Storage sticks around. It survives page reloads, browser tabs, and even full shutdowns. This makes it perfect for situations where you want a user’s data to “live on” in their browser. In this article, we’ll explore only how to use Local Storage step by step. We’ll walk through real, working code examples using characters and scenarios from daily life — like saving Harry’s favorite spell or tracking Brian’s visits to a dog facts page.

Setting Data in Local Storage

Before you can retrieve any data from Local Storage, you need to put it there. The basic way to do that is by using the localStorage.setItem() method. This method takes two strings: a key and a value. The key is the name you’ll use to retrieve the value later.

Let’s imagine Harry wants to save his favorite spell.

<!DOCTYPE html>
<html>
<head>

  <title>Web API | Local Storage</title>

</head>
<body>

  <script>

    localStorage.setItem("favoriteSpell", "Expelliarmus");

  </script>

</body>
</html>

Here, localStorage.setItem("favoriteSpell", "Expelliarmus") stores the string "Expelliarmus" in the browser’s Local Storage with the key "favoriteSpell". That means as long as the storage isn’t cleared, Harry’s spell will stay saved — even after closing or refreshing the page. Remember that Local Storage only accepts string values, so anything you store must either be a string or converted into one.

Getting Data from Local Storage

Once data is stored, you’ll often want to read it back. You do this with localStorage.getItem(key). This method will return the value associated with the key you pass in. If no value exists for that key, it will return null.

Let’s now retrieve Harry’s favorite spell:

<!DOCTYPE html>
<html>
<head>

  <title>Web API | Local Storage</title>

</head>
<body>

  <script>

    const spell = localStorage.getItem("favoriteSpell");
    console.log(spell); // Output: Expelliarmus

  </script>

</body>
</html>

This code fetches the value from storage and logs it. If the key exists, you get the value; if not, you’ll get null, so it’s a good idea to check before using it in a real application.

Removing a Specific Item

Sometimes, the data you store becomes outdated or irrelevant. You can remove a specific entry from Local Storage using localStorage.removeItem(key). Let’s say Harry has changed his favorite spell and wants to clear the old one.

<!DOCTYPE html>
<html>
<head>

  <title>Web API | Local Storage</title>

</head>
<body>

  <script>


    localStorage.removeItem("favoriteSpell");

    const spell = localStorage.getItem("favoriteSpell");

    if(spell)
      console.log(spell); // Output: Expelliarmus
    else
      console.log('Spell not found...');

  </script>

</body>
</html>

Here, localStorage.removeItem("favoriteSpell") deletes the "favoriteSpell" entry entirely from Local Storage. The next time you try to get that value, it will return null, because it no longer exists.

Clearing All Data

If you want to remove everything stored in Local Storage — maybe for a complete reset — you can use localStorage.clear(). This method deletes all key-value pairs, not just one.

Imagine Stewie has a game and wants to let the user reset all progress:

<!DOCTYPE html>
<html>

<head>

  <title>Web API | Local Storage</title>

</head>

<body>

  <script>

    function getSpell() {

      const spell = localStorage.getItem("favoriteSpell");

      if (spell)
        console.log(spell);
      else
        console.log('Spell Not Found...');

    }

    localStorage.setItem("favoriteSpell", "Expelliarmus");
    getSpell();  // Output: Expelliarmus

    localStorage.clear();
    getSpell(); // Output: Spell Not Found...

  </script>

</body>

</html>

Executing localStorage.clear() will wipe all local storage data from the current domain. Be careful — it’s irreversible unless you have the values saved somewhere else.

Storing Objects and Arrays Using JSON

Since Local Storage only supports strings, you can’t store arrays or objects directly. But there’s a simple trick: use JSON.stringify() to convert the object or array into a string before storing it, and use JSON.parse() to convert it back when retrieving it.

Let’s say Lucia wants to save her favorite dog breeds:

<!DOCTYPE html>
<html>

<head>

  <title>Web API | Local Storage</title>

</head>

<body>

  <script>

    const dogs = ["Beagle", "German Shepherd", "Bulldog"];
    localStorage.setItem("luciaDogs", JSON.stringify(dogs));

  </script>

</body>

</html>

In the example above, the array of dog breeds is turned into a string and saved. Now let’s retrieve and use it later:

<!DOCTYPE html>
<html>

<head>

  <title>Web API | Local Storage</title>

</head>

<body>

  <script>

    const dogsFromStorage = JSON.parse(localStorage.getItem("luciaDogs"));
    console.log(dogsFromStorage); // Output: ["Beagle", "German Shepherd", "Bulldog"]

  </script>

</body>
</html>

Using JSON.stringify() and JSON.parse() makes it possible to work with complex data structures inside Local Storage.

Checking If a Key Exists

Before using a value from Local Storage, it’s sometimes useful to check whether it’s there. You can do this simply by comparing the result of getItem() to null.

Suppose Stewie wants to check if a weapon is loaded:

<!DOCTYPE html>
<html>

<head>

  <title>Web API | Local Storage</title>

</head>

<body>

  <script>

    if (localStorage.getItem("laserGun") !== null) {
      console.log("Armed and ready!");
    } else {
      console.log("No laser gun found.");
    }

  </script>

</body>
</html>

This check ensures the key exists before relying on its value. It’s a safe way to avoid surprises when accessing Local Storage.

Updating Existing Data

Updating a value in Local Storage is done the same way as setting it — just use setItem() again with the same key. The new value will overwrite the old one.

If Hermione originally saved her favorite language as Python, but later changed her mind to JavaScript, she could update it like this:

<!DOCTYPE html>
<html>

<head>

  <title>Web API | Local Storage</title>

</head>

<body>

  <script>

    function getLanguage() {
      const language = localStorage.getItem("favLang");
      console.log(language);
    }

    localStorage.setItem("favLang", "Python");
    getLanguage();

    localStorage.setItem("favLang", "JavaScript");
    getLanguage();

  </script>

</body>
</html>

After this update, any call to getItem("favLang") will now return "JavaScript" instead of "Python". Simple and effective.

Using Local Storage with User Events

Local Storage becomes even more useful when combined with user interactions, like form inputs or dropdowns. You can capture user preferences and store them immediately in the browser.

Let’s say you have a movie selector, and you want to save the last selected movie so the user doesn’t have to pick it again next time:

<!DOCTYPE html>
<html>

<head>

  <title>Web API | Local Storage</title>

</head>

<body>

  <form>

    <select id="movieSelect">
      <option value="Lion King">Lion King</option>
      <option value="Black Panther">Black Panther</option>
      <option value="Shaka Zulu">Shaka Zulu</option>
    </select>

  </form>

  <script>

    document.getElementById("movieSelect").addEventListener("change", function (e) {
      localStorage.setItem("selectedMovie", e.target.value);
    });

  </script>

</body>
</html>

Here, whenever the dropdown changes, the selected movie gets saved to Local Storage. You could easily write more code to pre-fill the selection on page load using that saved value.

Writing a Page View Stat Tracker

One fun use of Local Storage is to build a stat tracker that keeps count of how many times a user has visited a particular page. Let’s do this with Brian, who is obsessed with the Dog Facts page.

Every time he opens the page, the view counter goes up:

<!DOCTYPE html>
<html>

<head>

  <title>Web API | Local Storage</title>

</head>

<body>

  <p id="output"></p>

  <script>

    let visits = localStorage.getItem("dogPageViews");

    // If visits is null (first time), start from 0
    visits = visits ? parseInt(visits) : 0;

    // Increase the visit count by 1
    visits++;

    // Save the updated count back to Local Storage
    localStorage.setItem("dogPageViews", visits);

    // Show the number of visits
    document.getElementById("output").textContent = `You've viewed this page ${visits} times.`;

  </script>

</body>
</html>

This code first checks if a view count exists. If not, it sets it to 0. Then it increments the number and stores it again. As a result, the number of visits will be remembered every time Brian comes back — even weeks later!

Conclusion

In this article, we explored how to use JavaScript’s Local Storage to save, read, update, and delete data directly in the browser. We learned how to store not only strings but also arrays and objects using JSON. We saw how to combine Local Storage with user events and even how to build a page view tracker using simple code.

Local Storage gives your web apps a sense of memory — a way to hold on to information between sessions, without needing a server. It’s simple, powerful, and incredibly useful for creating dynamic, personalized experiences on the web.

References

If you want to learn more about JavaScript Local Storage and related topics, these resources are excellent starting points:

Scroll to Top