🟨 JavaScript tutorial for beginners · Class 8 · Lesson 13 of 18 · Free
Local Storage – Make Your Web Page Remember Things
⏱ About 30 minutes · ▶ run real JavaScript here — nothing to install · no sign-in
In this lesson you will
- Save and read values with localStorage.setItem() and getItem()
- Store arrays and objects using JSON.stringify() and JSON.parse()
- Build a page that remembers a setting after a reload
You set a new high score in your game, close the tab, and come back. The score shows 0 again! Web pages forget everything when you reload them. In this lesson, you give your page a small memory box that stays even after you close the browser.
What is localStorage in JavaScript?
Normally, every variable disappears when the page reloads. `localStorage` is a small storage box inside the browser that keeps data even after you close it.
It works like a cupboard with labelled boxes. Each box has a **key** (the label) and a **value** (what is inside). `setItem(key, value)` puts something in. `getItem(key)` takes it out.
The data stays on this computer, in this browser, for this website only. Other websites cannot read it.
▶localStorage.setItem("username", "Asha");2localStorage.setItem("city", "Pune");34const name = localStorage.getItem("username");5const city = localStorage.getItem("city");6console.log(`Welcome back, ${name} from ${city}!`);78// a key that was never saved gives null9console.log(localStorage.getItem("school"));
No variables yet.
▌✏️ Change this code and run it yourself
Welcome back, Asha from Pune!null
💡 Try it: change "Asha" to your own name and run again.
Why does localStorage turn my number into a string?
localStorage can only keep **text** (strings). If you save the number 10, it is stored as the text "10".
So when you read it back, `+` joins text instead of adding. "10" + 5 becomes "105", not 15!
The fix: wrap the value in `Number()` after you read it. You met `Number()` in Lesson 2.
▶localStorage.setItem("coins", 10);23const saved = localStorage.getItem("coins");4console.log(typeof saved); // string!5console.log(saved + 5); // joins text67const coins = Number(saved);8console.log(typeof coins);9console.log(coins + 5); // real adding
No variables yet.
▌✏️ Change this code and run it yourself
string105number15
How do I count how many times someone visited my page?
This is the classic localStorage trick. Read the old count, add 1, and save it again.
The first time, there is no "visits" box, so `getItem` gives `null`. `Number(null)` is 0, so the count starts at 0 + 1 = 1.
Press ▶ Run a few times. The number keeps growing, because the lesson page remembers it between runs!
Hello! This is your first visit 👋
💡 The output here shows a first visit. On your screen it counts up each time you press Run.
How do I save an array or object in localStorage with JavaScript?
If you save an array directly, localStorage turns it into plain text like "92,85,78". You lose the array!
The fix is **JSON**, a text format for data. `JSON.stringify(data)` turns an array or object into text. `JSON.parse(text)` turns that text back into a real array or object.
Remember the pair: **stringify to save, parse to load**.
▶const player = { name: "Rohan", level: 3, scores: [92, 85, 78] };23const text = JSON.stringify(player);4console.log(text);5localStorage.setItem("player", text);67const loaded = JSON.parse(localStorage.getItem("player"));8console.log(loaded.name, "is on level", loaded.level);9console.log("First score:", loaded.scores[0]);
No variables yet.
▌✏️ Change this code and run it yourself
{"name":"Rohan","level":3,"scores":[92,85,78]}Rohan is on level 3First score: 92
💡 Try it: add a new key like city: "Nagpur" to the object and print loaded.city.
How do I make a dark mode that is remembered after reload?
Here is a real use: a theme switch. When you click the button, the page changes colour and saves your choice.
When the page loads, the first lines read the saved theme and use it. So the page opens the way you left it.
Click the button, then press ▶ Run again. The page starts in the theme you chose.
📄 HTML of the page (tap to see / edit)
Saved theme: null
How do I delete data from localStorage?
`removeItem(key)` deletes one box. `clear()` empties the whole cupboard for this website.
Use `removeItem` for a "Log out" or "Reset score" button. Be careful with `clear()`: it deletes everything your site saved.
Tip: in Chrome you can see the boxes yourself. Press F12, open the Application tab, then Local Storage.
Score before: 250Score now: nullName still: AshaAfter clear: 0 boxes
🤔 Predict the output
Think like JavaScript: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
localStorage.setItem("score", 10);
const s = localStorage.getItem("score");
console.log(s + 5);Question 2. What does this print?
localStorage.removeItem("rollNo");
console.log(localStorage.getItem("rollNo"));Question 3. What does this print?
localStorage.setItem("bag", ["pen", "book"]);
console.log(localStorage.getItem("bag"));🧩 Your challenge
Build a **high score saver**. For each score in `games`, read the best score from localStorage. If the new score is bigger, save it and print a "New high score" line. Otherwise print that the best stays. At the end print the saved best. Expected output: ``` 🏆 New high score: 42 🏆 New high score: 77 65 — best is still 77 Saved best: 77 ```
🏆 New high score: 42 🏆 New high score: 77 65 — best is still 77 Saved best: 77
⚠️ Common mistakes (and how to fix them)
❌ Wrong
const user = { name: "Asha", age: 13 };
localStorage.setItem("user", user);
const back = JSON.parse(localStorage.getItem("user"));
console.log(back.name);SyntaxError: "[object Object]" is not valid JSON
✅ Right
const user = { name: "Asha", age: 13 };
localStorage.setItem("user", JSON.stringify(user));
const back = JSON.parse(localStorage.getItem("user"));
console.log(back.name);An object saved without JSON.stringify becomes the useless text "[object Object]". Always stringify before saving.
❌ Wrong
localStorage.setItem("pocketMoney", 200);
const money = localStorage.getItem("pocketMoney") + 50;
console.log(`You have ₹${money}`);No error, but it prints ₹20050 instead of ₹250, because "200" + 50 joins the text.
✅ Right
localStorage.setItem("pocketMoney", 200);
const money = Number(localStorage.getItem("pocketMoney")) + 50;
console.log(`You have ₹${money}`);getItem always gives a string. Turn it into a number with Number() before doing maths.
❌ Wrong
localStorage.removeItem("homework");
const list = JSON.parse(localStorage.getItem("homework"));
list.push("Maths sums");
console.log(list);TypeError: Cannot read properties of null (reading 'push')
✅ Right
localStorage.removeItem("homework");
const list = JSON.parse(localStorage.getItem("homework")) || [];
list.push("Maths sums");
console.log(list);The first time, nothing is saved, so the list is null. Add || [] to start with an empty array when nothing was saved.
📌 Remember
- localStorage keeps data in the browser even after you close it.
- setItem(key, value) saves, getItem(key) reads, removeItem(key) deletes one, clear() deletes all.
- getItem gives null when the key was never saved.
- Everything is stored as text: use Number() for numbers.
- For arrays and objects: JSON.stringify to save, JSON.parse to load.
Finished the quiz and the challenge?
Questions students ask
What is localStorage in JavaScript?
localStorage is a small storage area in the browser. A website can save text there with a key, and read it back later. The data stays even after the browser is closed and opened again.
How much data can localStorage hold?
Most browsers allow about 5 MB per website. That is plenty for settings, scores and to-do lists, but not for photos or videos.
Is localStorage safe for passwords?
No. Anyone using that computer can open DevTools and read it. Never store passwords or secret information in localStorage.
What is the difference between localStorage and sessionStorage?
They work the same way. But sessionStorage is cleared when you close the tab, while localStorage stays until it is deleted.