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.