JavaScript Local Storage

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.

local-storage.js
localStorage.setItem("username", "Alex");
const name = localStorage.getItem("username");
console.log(name); // "Alex" — still there after a refresh

Let’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 in name.
  • 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:

local-storage.js
localStorage.setItem("theme", "dark"); // save
console.log(localStorage.getItem("theme")); // "dark" — read
localStorage.removeItem("theme"); // delete one item
localStorage.clear(); // delete everything

Here’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.

local-storage.js
const user = { name: "Alex", level: 5 };
// ✅ save an object by turning it into a string
localStorage.setItem("user", JSON.stringify(user));
// ✅ read it back and turn the string into an object
const 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 to setItem, so storage receives text it can actually hold.
  • localStorage.getItem("user") reads back that string, and JSON.parse(...) turns the string back into a real object we can use.
  • console.log(savedUser.name) prints "Alex", which only works because JSON.parse rebuilt the object. Without it, savedUser would 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.

local-storage.js
const todos = ["Learn JavaScript", "Build a project", "Take a break"];
// save the array
localStorage.setItem("todos", JSON.stringify(todos));
// later, read it back
const savedTodos = JSON.parse(localStorage.getItem("todos"));
savedTodos.push("Review notes");
// save the updated array again
localStorage.setItem("todos", JSON.stringify(savedTodos));
console.log(savedTodos); // the full list, with the new item

Here’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, and setItem saves that string under the key "todos".
  • JSON.parse(localStorage.getItem("todos")) reads the string back and turns it into a real array again, stored in savedTodos.
  • savedTodos.push("Review notes") adds a new item to that array, which works because JSON.parse gave us an actual array with array methods.
  • We call JSON.stringify and setItem once 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.

local-storage.js
// when the user picks a theme
localStorage.setItem("theme", "dark");
// when the page loads, apply the saved theme
const 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, getItem returns null, so theme becomes "light" instead.
  • document.body.className = theme applies 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!

  1. Use setItem to save a username, then read it back with getItem and print it.
  2. Save an object with JSON.stringify, read it with JSON.parse, and print one of its properties.
  3. Save an array of to-do items, add a new item, and save the updated array.
  4. Call getItem with a key you never set and confirm it returns null.
  5. Use removeItem to delete one key, then clear() to empty storage.

🧩 What You’ve Learned

  • localStorage saves key-value data that persists after the page is closed
  • ✅ The four methods are setItem, getItem, removeItem, and clear
  • ✅ Everything is stored as a string
  • ✅ Use JSON.stringify to save objects and arrays, and JSON.parse to read them back
  • getItem returns null when 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.

Share & Connect