JavaScript Local Storage
Table of Contents + −
In the previous lesson, we learned how to catch and handle errors so our code keeps running. Now let’s look at our first Browser API, localStorage, which lets us save data in the browser so it stays around even after the page is closed.
💾 What is localStorage?
localStorage is a small storage box built into the browser. It stores data as key-value pairs, and that data persists even after the user closes the tab, closes the browser, or restarts the computer. When they come back to your page, the data is still there.
This makes it perfect for remembering a user’s preferences, like a chosen theme, or saving a small amount of data between visits.
localStorage.setItem("username", "Alex");
const name = localStorage.getItem("username");console.log(name); // "Alex" — still there after a refreshLet’s walk through what each line does:
localStorage.setItem("username", "Alex")saves the value"Alex"under the key"username". The key is the label we use to find the value later.localStorage.getItem("username")looks up that key and returns its value, which we store inname.console.log(name)prints"Alex", and that value is still there even after the page reloads.
🧰 The Four Methods
localStorage gives you four methods to work with. The first part of each line below is the method name, and the rest shows what it does.
| Method | What it does | Example |
setItem(key, value) | Saves a value under a key | localStorage.setItem("theme", "dark") |
getItem(key) | Reads the value for a key | localStorage.getItem("theme") |
removeItem(key) | Deletes one key and its value | localStorage.removeItem("theme") |
clear() | Deletes everything in storage | localStorage.clear() |
Here they are together in code:
localStorage.setItem("theme", "dark"); // saveconsole.log(localStorage.getItem("theme")); // "dark" — readlocalStorage.removeItem("theme"); // delete one itemlocalStorage.clear(); // delete everythingHere’s what each line does:
setItem("theme", "dark")saves the value"dark"under the key"theme".getItem("theme")reads that value back, so the log prints"dark".removeItem("theme")deletes just the"theme"key and its value, leaving the rest of storage alone.clear()wipes out every key in storage, not just one.
🔤 Everything is Stored as a String
localStorage can only store strings. If you try to save a number, it gets turned into text. More importantly, if you try to save an object or an array directly, you get the useless text "[object Object]" instead of your data.
The fix is to convert your object or array into a string with JSON.stringify before saving, and convert it back with JSON.parse when reading.
const user = { name: "Alex", level: 5 };
// ✅ save an object by turning it into a stringlocalStorage.setItem("user", JSON.stringify(user));
// ✅ read it back and turn the string into an objectconst savedUser = JSON.parse(localStorage.getItem("user"));console.log(savedUser.name); // "Alex"Let’s go through this line by line:
const user = { name: "Alex", level: 5 }creates an object we want to save.JSON.stringify(user)turns that object into a string like'{"name":"Alex","level":5}'. We pass that string tosetItem, so storage receives text it can actually hold.localStorage.getItem("user")reads back that string, andJSON.parse(...)turns the string back into a real object we can use.console.log(savedUser.name)prints"Alex", which only works becauseJSON.parserebuilt the object. Without it,savedUserwould still be a plain string.
Remember the pair
JSON.stringify goes in, JSON.parse comes out. Whenever you store an object
or array, you will use both.
🎨 A Practical Example: Saving a To-Do List
Let’s save an array of to-do items. Because it is an array, we stringify it on the way in and parse it on the way out.
const todos = ["Learn JavaScript", "Build a project", "Take a break"];
// save the arraylocalStorage.setItem("todos", JSON.stringify(todos));
// later, read it backconst savedTodos = JSON.parse(localStorage.getItem("todos"));savedTodos.push("Review notes");
// save the updated array againlocalStorage.setItem("todos", JSON.stringify(savedTodos));
console.log(savedTodos); // the full list, with the new itemHere’s what happens step by step:
const todos = [...]creates an array of three to-do items.JSON.stringify(todos)turns the array into a string, andsetItemsaves that string under the key"todos".JSON.parse(localStorage.getItem("todos"))reads the string back and turns it into a real array again, stored insavedTodos.savedTodos.push("Review notes")adds a new item to that array, which works becauseJSON.parsegave us an actual array with array methods.- We call
JSON.stringifyandsetItemonce more to save the updated array, overwriting the old value under the same key. console.log(savedTodos)prints the full list, now including"Review notes".
The same approach works for a theme preference. You read the saved theme when the page loads and apply it, so the user’s choice is remembered.
// when the user picks a themelocalStorage.setItem("theme", "dark");
// when the page loads, apply the saved themeconst theme = localStorage.getItem("theme") || "light";document.body.className = theme;Let’s break this down:
setItem("theme", "dark")saves the user’s choice when they pick a theme.getItem("theme") || "light"reads the saved theme, and the|| "light"part supplies a fallback: if the key was never set,getItemreturnsnull, sothemebecomes"light"instead.document.body.className = themeapplies that value as a CSS class on the page body, so the saved look is restored on load.
📏 Limits and Safety
localStorage is handy, but it has limits you should keep in mind. It holds about 5MB per origin, which is a website’s protocol, domain, and port together. Data saved on one site cannot be read by another site.
It is also not secure. Anyone with access to the browser can open the developer tools and read everything in localStorage.
Never store secrets
Do not save passwords, tokens, or any sensitive data in localStorage. It is
plain text that any script on your page can read.
⚠️ Common Mistakes to Avoid
| Mistake | Problem | Solution |
Saving an object without JSON.stringify | You get the text "[object Object]", not your data | Wrap objects and arrays in JSON.stringify |
Reading without JSON.parse | You get a string, so .name or .push fails | Wrap the result in JSON.parse |
| Assuming a key always exists | getItem returns null when the key is missing | Check for null or use a fallback like || "light" |
| Storing sensitive data | Anyone can read it in the developer tools | Keep passwords and tokens out of localStorage |
🔧 Try It Yourself!
- Use
setItemto save a username, then read it back withgetItemand print it. - Save an object with
JSON.stringify, read it withJSON.parse, and print one of its properties. - Save an array of to-do items, add a new item, and save the updated array.
- Call
getItemwith a key you never set and confirm it returnsnull. - Use
removeItemto delete one key, thenclear()to empty storage.
🧩 What You’ve Learned
- ✅
localStoragesaves key-value data that persists after the page is closed - ✅ The four methods are
setItem,getItem,removeItem, andclear - ✅ Everything is stored as a string
- ✅ Use
JSON.stringifyto save objects and arrays, andJSON.parseto read them back - ✅
getItemreturnsnullwhen a key is missing - ✅ Storage is about 5MB per origin and is not secure for sensitive data
🚀 What’s Next?
Now that you can save data that lasts, let’s look at storage that clears itself when the tab closes. Let’s continue to Session Storage.