All posts
JavaScriptNovember 1, 20267 min read

JavaScript localStorage for Beginners: Save Data Easily

Learn how to use JavaScript localStorage step by step. Save, read and delete data in the browser with simple, copy-paste examples made for absolute beginners.

F
Fepiq Team
Fepiq

How do you save data in JavaScript so it is still there after the page reloads? The simple answer is localStorage. It is a small storage box built into every web browser. You put a value in with setItem, take it out with getItem, and the browser keeps it, even after you close the tab or restart the computer.

In this beginner guide you will learn what localStorage is, how to save, read and delete data, how to store arrays and objects, and which mistakes to avoid. You do not need any earlier experience beyond basic variables and functions.

What is localStorage?

localStorage is a feature of the browser that lets a website save small pieces of text on the visitor's own device. Each piece is saved as a key and a value. The key is a name (like "theme"). The value is the data (like "dark"). Think of it as a labelled drawer: the label is the key, and what is inside is the value.

Normal JavaScript variables disappear when the page reloads. localStorage data stays. That makes it perfect for things like a dark mode choice, a user's name, or a simple to-do list.

Save data with setItem

Use localStorage.setItem(key, value) to save something. Open your browser, press F12, go to the Console tab, and try this.

js
localStorage.setItem("username", "Sam");
localStorage.setItem("theme", "dark");

Line 1 saves the value "Sam" under the key "username". Line 2 saves "dark" under the key "theme". Both keys and values are written inside quotes because they are text (called strings). If you save to a key that already exists, the old value is replaced.

Read data with getItem

Use localStorage.getItem(key) to read a value back.

js
const name = localStorage.getItem("username");
console.log(name); // Sam

const missing = localStorage.getItem("age");
console.log(missing); // null

The first line reads the value stored under "username" and puts it in a variable called name. The console then prints Sam. The third line asks for a key that does not exist. In that case getItem gives back null, which means "nothing here". Always be ready for null when you read data.

Remove data with removeItem and clear

js
localStorage.removeItem("theme");
localStorage.clear();

removeItem deletes just one key, here "theme". clear deletes everything your website has saved in localStorage. Use clear carefully, because there is no undo.

The four main methods at a glance

MethodWhat it doesExample
setItem(key, value)Saves or updates a valuelocalStorage.setItem("theme", "dark")
getItem(key)Reads a value (or null)localStorage.getItem("theme")
removeItem(key)Deletes one keylocalStorage.removeItem("theme")
clear()Deletes all keyslocalStorage.clear()

A practical example: remember dark mode

Let us build something useful. This code saves the visitor's theme choice and applies it again the next time they open the page. If you are new to changing the page with JavaScript, read our DOM manipulation guide first.

js
const button = document.querySelector("#toggle");

const saved = localStorage.getItem("theme");
if (saved === "dark") {
  document.body.classList.add("dark");
}

button.addEventListener("click", () => {
  document.body.classList.toggle("dark");
  const isDark = document.body.classList.contains("dark");
  localStorage.setItem("theme", isDark ? "dark" : "light");
});

Line 1 finds the button on the page. Line 3 reads the saved theme. Lines 4 to 6 say: if the saved theme is dark, add the dark class to the page right away. Line 8 listens for clicks on the button. Inside, line 9 switches the dark class on or off, line 10 checks whether it is now on, and line 11 saves "dark" or "light" so the choice is remembered. Reload the page and your choice stays.

New to changing page elements with JavaScript? Read our DOM manipulation guide for beginners before building more examples.

Read the DOM guide

Why objects and arrays need JSON

localStorage can only store strings. If you try to save an array or object directly, JavaScript turns it into useless text.

js
localStorage.setItem("fruits", ["apple", "banana"]);
console.log(localStorage.getItem("fruits")); // apple,banana

The result is the plain text "apple,banana", not a real array. You cannot loop over it or use array methods. To fix this, convert the data to a JSON string when saving and convert it back when reading. JSON is just a text format for data.

Save arrays and objects with JSON.stringify and JSON.parse

js
const todos = ["Buy milk", "Learn JavaScript"];
localStorage.setItem("todos", JSON.stringify(todos));

const text = localStorage.getItem("todos");
const list = JSON.parse(text);
console.log(list[1]); // Learn JavaScript

Line 1 creates an array. Line 2 uses JSON.stringify to turn the array into the string '["Buy milk","Learn JavaScript"]' and saves it. Line 4 reads the string. Line 5 uses JSON.parse to turn it back into a real array. Line 6 prints the second item. The same two steps work for objects.

Handle missing data safely

js
const todos = JSON.parse(localStorage.getItem("todos")) || [];
todos.push("Write a blog post");
localStorage.setItem("todos", JSON.stringify(todos));

On the first visit, nothing is saved, so getItem returns null and JSON.parse(null) gives null. The || [] part means "or else use an empty array". Then we add a new item with push and save the updated list again. This read, change, save pattern is how most small apps use localStorage.

localStorage vs sessionStorage vs cookies

FeaturelocalStoragesessionStorageCookies
Lasts untilYou delete itThe tab is closedAn expiry date
Size limitAbout 5 MBAbout 5 MBAbout 4 KB
Sent to serverNoNoYes, on every request
Best forPreferences, small app dataTemporary tab dataLogin sessions

sessionStorage works exactly like localStorage, with the same methods, but its data disappears when the tab closes. Cookies are tiny and are sent to the server with each request, so they suit things like logins.

Common beginner mistakes

  • Saving passwords or private data. Anyone using that browser, or any script on your page, can read localStorage. Never store secrets in it.
  • Forgetting JSON.stringify and JSON.parse for arrays and objects.
  • Not handling null when a key has never been saved.
  • Expecting numbers to stay numbers. localStorage.setItem("age", 25) is read back as the string "25". Use Number() to convert it.
  • Expecting data to sync across devices. It lives only in one browser on one device.

Quick practice ideas

  1. Save a visitor's name and show "Welcome back, name" on the next visit.
  2. Build a page visit counter that adds 1 each time the page loads.
  3. Make a to-do list that keeps its items after a reload.

Frequently asked questions

What is localStorage in JavaScript?+

localStorage is a built-in browser feature that saves key and value pairs on the visitor's device. The data stays after the page reloads or the browser closes. It is used for small things like settings and simple app data.

How long does localStorage data last?+

It lasts until you or the user deletes it. It has no expiry date. A user can clear it from the browser settings, and private browsing windows usually erase it when closed.

How do I store an array or object in localStorage?+

Convert it to a string with JSON.stringify before saving it with setItem. When you read it with getItem, turn it back using JSON.parse. This keeps its structure intact.

How much data can localStorage hold?+

Most browsers allow about 5 MB per website. That is plenty for settings and small lists, but too small for large files or big databases.

Is localStorage safe for passwords?+

No. Data in localStorage is not encrypted and can be read by any script running on your page. Keep passwords and other sensitive data on the server instead.

Next steps

You now know how to save, read and delete data in the browser. Try the practice ideas above, then combine localStorage with event listeners and arrays to build small apps that remember what users do.

Want help turning your idea into a real web app? Talk to the Fepiq team.

Contact Fepiq

Get new posts in your inbox

Occasional, no-fluff notes on shipping modern software — startups, automation, Laravel, Shopify and more. No spam, unsubscribe anytime.

Keep reading

Related posts

All posts

Let's build something

Ready to ship your next product with Fepiq?

Book a free discovery call. We'll listen, ask sharp questions, and send you a proposal within 3 business days.