How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Use localStorage in JavaScript (With Real Examples + Troubleshooting)
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > 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.
[mc4wp_form]
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
Most Popular
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026
Tailscale mesh — peer-to-peer connections between devices, coordination server
How to Install Tailscale on Ubuntu (Zero-Config Mesh VPN for Self-Hosters)
May 24, 2026
Caddy server — automatic HTTPS, 3-line Caddyfile vs 25-line nginx config
How to Install Caddy Server on Ubuntu (Automatic HTTPS, Drop-in nginx Alternative)
May 24, 2026
Cloudflare Tunnel — outbound-only connection from server, no inbound port forward
How to Install Cloudflare Tunnel on Ubuntu (Expose Local Services, No Port Forwarding)
May 24, 2026
WireGuard encrypted tunnel between server and clients with lock icons
How to Set Up WireGuard VPN on Ubuntu (Server, Linux Client, and iOS)
May 24, 2026

You Might Also Like

Display PHP errors — ini_set + php.ini configuration
Web Development

How to Display PHP Errors

7 Min Read
Duplicate a div into another div with jQuery clone
Web Development

How to Duplicate a DIV into Another DIV with jQuery

4 Min Read
WooCommerce remove checkout fields — woocommerce_checkout_fields filter unsetting fields
Web Development

How to Remove Checkout Fields in WooCommerce

6 Min Read
Get the last item from a PHP array
Web Development

How to Get the Last Item from an Array in PHP

5 Min Read
How7o

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

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?