How to Use localStorage in JavaScript

Bridget AmanaBridget Amana
2 min read

You know when you accidentally close a form just before you're done filling it out, and when you reopen the page, all your info is still there?
That’s localStorage at work.

localStorage is a feature in JavaScript that allows developers to store data directly in the browser. In this article, we’ll look at what localStorage is (and what it isn’t) and walk through a quick demo on how to use it.

What local storage is and isn’t

localStorage is a built-in feature of modern browsers that lets you store data with no expiration. That means the data stays saved in the browser until it’s manually cleared either by your code or by the user.

That data is only stored on the specific browser and device where it was created. So, if you log into the same app on a different browser or phone, don’t expect your localStorage data to follow you. It’s not synced or tied to any user account.

How does local storage work?

  • To set an item:

      localStorage.setItem("myCat", "Tom");
    
  • To get an item:

      localStorage.getItem("myCat");
    
  • To remove a specific item:

      localStorage.removeItem("myCat");
    
  • To clear everything:

      localStorage.clear();
    

Save and Retrieve Data Using localStorage

Open your DevTools (right-click → Inspect → Console tab) and try this:

Start by saving something:

localStorage.setItem("username", "bridget");

Nothing happens, it just runs. But behind the scenes, your browser has stored the word "bridget" under the name "username".

Now let’s check if it worked:

localStorage.getItem("username");

You should see:

"bridget"

That means it worked. The value is saved in your browser.

Now let’s remove it:

localStorage.removeItem("username");

And try to get it again:

localStorage.getItem("username");

This time, you’ll get:

null

That’s the browser telling you: “There’s nothing stored with that name anymore.”

You can also overwrite a value anytime by using setItem again with a different value:

localStorage.setItem("username", "you");
localStorage.getItem("username");

Now the saved value is "you" instead of "bridget".

Conclusion

localStorage is super useful for keeping small pieces of data on the browser things like form inputs, theme preferences, or draft content. It’s not a replacement for a database, but it’s a great tool for quick, lightweight storage.

You’ve seen how easy it is to use just a few lines of code, and your site becomes a bit more user-friendly.
Play around with it. Try storing more values. You’ll get the hang of it fast.

0
Subscribe to my newsletter

Read articles from Bridget Amana directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Bridget Amana
Bridget Amana

I write on web development, CSS, JavaScript, and accessibility. I simplify complex topics to help developers build better, more inclusive web experiences.