How7o
  • Home
  • Marketing
    MarketingShow More
  • OS
    OSShow More
    How to force quit frozen apps in Ubuntu
    Force Close an App in Ubuntu (xkill, System Monitor, kill -9)
    4 Min Read
  • Features
    FeaturesShow More
  • Guide
    GuideShow More
  • Contact
  • Blog
Reading: How to Use localStorage in JavaScript (With Real Examples + Troubleshooting)
Share
Subscribe Now
How7oHow7o
Font ResizerAa
  • Marketing
  • OS
  • Features
  • Guide
  • Complaint
  • Advertise
Search
  • Categories
    • Marketing
    • OS
    • Features
    • Guide
    • Lifestyle
    • Wellness
    • Healthy
    • Nutrition
  • More Foxiz
    • Blog Index
    • Complaint
    • Sitemap
    • Advertise
Follow US
Copyright © 2014-2023 Ruby Theme Ltd. All Rights Reserved.
How7o > Blog > Web Development > How to Use localStorage in JavaScript (With Real Examples + Troubleshooting)
Web Development

How to Use localStorage in JavaScript (With Real Examples + Troubleshooting)

how7o
By how7o
Last updated: February 6, 2026
8 Min Read
How to use localStorage in JavaScript shown in a browser storage panel
SHARE

I recently needed a simple way to remember user preferences on the client side—without a database, cookies, or building a full login system. That’s when I revisited how to use localStorage in JavaScript. It’s surprisingly powerful for small pieces of data like theme choice, dismissed banners, form drafts, and basic app state.

Contents
  • What is localStorage?
  • Before you start: check if localStorage is supported
  • How to use localStorage in JavaScript (step-by-step)
    • Step 1: Store a simple value (string)
    • Step 2: Read the stored value
    • Step 3: Store an object (the “real world” case)
    • Step 4: Retrieve the object and convert it back
    • Step 5: Remove a single item or clear everything
  • A practical example: saving a theme preference
  • Troubleshooting localStorage issues
    • 1) “I stored an object but got ”
    • 2) JSON.parse throws an error
    • 3) localStorage throws “SecurityError” or “Access is denied”
    • 4) “It worked yesterday, now it’s empty”
    • 5) Storage quota issues
  • localStorage vs sessionStorage (quick comparison)
  • Official references (recommended)
  • Related guides
  • Wrap-up

In this post, I’ll walk you through what I learned the practical way: I hit a few common issues (like storing objects and handling missing support), then I built a clean, repeatable pattern. You’ll get examples you can copy/paste, plus troubleshooting tips that will save you time later.

What is localStorage?

localStorage is part of the Web Storage API (HTML5). It lets your browser store key/value pairs that persist even after you close the tab or restart the browser. Unlike cookies, localStorage data isn’t automatically sent to the server on every request. It stays on the client side, which makes it fast and easy for small bits of data.

Key points to remember:

  • Data is stored as strings (even if you “set” a number or object).
  • Storage is scoped per origin (domain + protocol + port).
  • It persists until you remove it (or the user clears site data).
  • It’s great for preferences and lightweight state—not for sensitive data.

Before you start: check if localStorage is supported

Most modern browsers support localStorage, but it’s still smart to check—especially if you’re building something that might run in older environments or locked-down browser settings.

if (typeof(Storage) !== "undefined") {
  // localStorage is supported
} else {
  // localStorage is not supported
}

In real projects, I prefer checking the actual object and wrapping access in try/catch (because some private modes or strict settings can throw errors).

function storageAvailable() {
  try {
    const testKey = "__storage_test__";
    window.localStorage.setItem(testKey, "1");
    window.localStorage.removeItem(testKey);
    return true;
  } catch (e) {
    return false;
  }
}

How to use localStorage in JavaScript (step-by-step)

localStorage works with simple operations: setItem, getItem, removeItem, and clear. Here’s how I use it in a clean, predictable way.

Step 1: Store a simple value (string)

localStorage.setItem("name", "John Doe");

This saves a key named name with the value John Doe. If the key already exists, it will be overwritten.

Step 2: Read the stored value

const name = localStorage.getItem("name");
console.log(name); // "John Doe"

If the key doesn’t exist, getItem() returns null. That’s important for avoiding runtime errors.

Step 3: Store an object (the “real world” case)

This is where many people get tripped up (I did too). localStorage only stores strings, so you must convert objects to JSON before saving.

const person = {
  name: "John Doe",
  location: "New York"
};

window.localStorage.setItem("user", JSON.stringify(person));

Now the stored value is a JSON string that looks like this:

{"name":"John Doe","location":"New York"}

Step 4: Retrieve the object and convert it back

const userString = localStorage.getItem("user");
const userObject = JSON.parse(userString);

console.log(userObject.name); // "John Doe"

If there’s a chance the key might not exist, handle null safely:

const userString = localStorage.getItem("user");
const userObject = userString ? JSON.parse(userString) : null;

if (userObject) {
  console.log("User:", userObject);
} else {
  console.log("No user found in localStorage.");
}

Step 5: Remove a single item or clear everything

When you want to reset just one value:

localStorage.removeItem("user");

When you want to wipe all storage for the current site/origin:

localStorage.clear();

A practical example: saving a theme preference

Here’s a pattern I often use in real projects: store a user preference like dark or light mode, then apply it on page load. This is one of the cleanest ways to demonstrate how to use localStorage in JavaScript without overcomplicating things.

// Save
function setTheme(theme) {
  localStorage.setItem("theme", theme);
  document.documentElement.dataset.theme = theme;
}

// Load
function loadTheme() {
  const saved = localStorage.getItem("theme") || "light";
  document.documentElement.dataset.theme = saved;
}

loadTheme();

This makes your UI feel “sticky” in a good way: the user sets a preference once, and your site remembers it.

Troubleshooting localStorage issues

When localStorage “doesn’t work,” it’s usually one of these problems. Here’s what to check before you lose an hour like I did.

1) “I stored an object but got [object Object]”

This happens when you try to store an object directly. Always use JSON.stringify() before saving and JSON.parse() after reading.

2) JSON.parse throws an error

If the stored value is not valid JSON (or the key is missing and returns null), parsing can fail. Use a safe helper:

function getJSON(key, fallback = null) {
  const raw = localStorage.getItem(key);
  if (!raw) return fallback;

  try {
    return JSON.parse(raw);
  } catch (e) {
    return fallback;
  }
}

3) localStorage throws “SecurityError” or “Access is denied”

This can happen in private browsing modes, embedded contexts (some iframes), or strict browser settings. Wrap your storage access in try/catch and fallback to in-memory variables if needed.

4) “It worked yesterday, now it’s empty”

The user may have cleared site data, switched browsers/devices, or you changed domain/protocol (for example from http to https). localStorage is tied to origin, so even small URL changes can isolate storage.

5) Storage quota issues

localStorage has limits (varies by browser). Don’t store big data, images, or large arrays. If you need that, look into IndexedDB instead.

localStorage vs sessionStorage (quick comparison)

If you’re deciding between them, here’s the simple rule I follow:

  • localStorage: persists until explicitly cleared.
  • sessionStorage: cleared when the tab/window closes (still per-origin, but tab-scoped).

For most “remember this preference” situations, localStorage wins.

Official references (recommended)

  • MDN: Window.localStorage
  • MDN: Web Storage API

Related guides

More WordPress-friendly guides you can link internally (replace these with your internal URLs when you have them):

  • How to use sessionStorage in JavaScript (with examples)
  • JavaScript JSON.stringify vs JSON.parse (common mistakes)
  • How to debug front-end issues using Chrome DevTools

Wrap-up

Once you understand that localStorage stores everything as strings, the rest clicks into place. If you remember only one thing from this guide on how to use localStorage in JavaScript, make it this: stringify objects when saving, parse them when reading, and always handle missing keys safely.

If you paste your next forum post, I’ll rewrite it into the same WordPress-ready format.

TAGGED:browser storageDebuggingfront-endHTML5JavaScriptJSON.parseJSON.stringifylocalStoragesessionStorageWeb Storage API

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Add commas to numbers in PHP using number_format() How to Add Commas to Numbers in PHP (Thousands Separator)
Next Article get .env variable in Laravel using env and config How to Get .env Variables in Laravel (Controller + Blade) Safely
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow

Subscribe Now

Subscribe to our newsletter to get our newest articles instantly!
Most Popular
Find prime numbers in JavaScript thumbnail
How to Find Prime Numbers in JavaScript (1 to 100) — Fast & Simple Methods
February 6, 2026
Dynamically set site title and tagline in WordPress by country
How to Dynamically Set Site Title and Tagline in WordPress (By Country)
February 6, 2026
Capitalize all words in JavaScript with a ucwords-style function
Capitalize All Words in JavaScript (ucwords Equivalent) + First Letter Uppercase
February 6, 2026
CSS page break for printing shown in a print preview layout
CSS Page Break for Printing: How to Split a Web Page Into Multiple Printed Pages
February 6, 2026
get .env variable in Laravel using env and config
How to Get .env Variables in Laravel (Controller + Blade) Safely
February 6, 2026

You Might Also Like

How I Fixed Composer Dependency Errors
Web Development

How I Fixed Composer Dependency Errors Using the –ignore-platform-reqs Flag (Step-by-Step Guide)

7 Min Read
Return or throw an error in Laravel (JSON response vs exception)
Web Development

How to Manually Return or Throw an Error Exception in Laravel

6 Min Read
Laravel Blade Time Format (HH:MM)
Web Development

How to Show Only Hours and Minutes in Laravel Blade (HH:MM)

3 Min Read
WooCommerce homepage filter to hide out of stock products
Web Development

Hide Out of Stock Products from Homepage in WooCommerce (Keep Them Visible Elsewhere)

5 Min Read

Always Stay Up to Date

Subscribe to our newsletter to get our newest articles instantly!
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Latest News

  • SEO Audit Tool
  • Client ReferralsNew
  • Execution of SEO
  • Reporting Tool

Resouce

  • Google Search Console
  • Google Keyword Planner
  • Google OptimiseHot
  • SEO Spider

Get the Top 10 in Search!

Looking for a trustworthy service to optimize the company website?
Request a Quote
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?