JavaScript Local Storage

Save data in the browser.

✍️ 3 exercises + code challenge in this lesson

The Web Storage API saves small amounts of data in the user's browser.

  • localStorage: kept even after the browser is closed.
  • sessionStorage: cleared when the tab is closed.

Methods: setItem(key, value), getItem(key), removeItem(key), clear(). Values are always strings, so use JSON.stringify / JSON.parse for objects.

Never store passwords or private data in localStorage: any script on the page can read it.

Key Takeaways: JavaScript Local Storage

Mastering JavaScript Local Storage helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Local Storage Code Example

JavaScript
<p>Visits counted in this browser: <strong id="visits">?</strong></p>
<button onclick="location.reload()">Reload</button>
<button onclick="reset()">Reset</button>

<script>
  let visits = 0;
  try {
    visits = Number(localStorage.getItem("visits") || 0) + 1;
    localStorage.setItem("visits", visits);
  } catch (e) {
    visits = "storage blocked in this frame";
  }
  document.getElementById("visits").textContent = visits;

  function reset() {
    try { localStorage.removeItem("visits"); } catch (e) {}
    location.reload();
  }
</script>
Free sign-in required · Google login available

JavaScript Local Storage Practice Exercises

Check what you learned in “JavaScript Local Storage”.

/ 3 solved
Fill in the blank

Save a value in the browser.

localStorage.("theme", "dark");
✓ Correct! Not quite. Try again.
Multiple choice

What type of values does localStorage store?

✓ Correct! Not quite. Try again.
Code challenge

Convert the object to a JSON string with JSON.stringify and log it.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services