Ad space (banner)
🎨HTML & CSS Lessons
Lesson 24 / 50

The Basics of localStorage (Saving Data in the Browser)

In this lesson you'll learn the basics of saving data in the browser with localStorage, so you can understand a mechanism that survives even after the page is closed. This is for people searching "localStorage usage."

localStorage is a "storage locker inside the browser" that doesn't get cleared when you close the page. You save with setItem() and retrieve with getItem(). This is used for things like preserving what someone typed into a to-do app.

The sample code saves a value with localStorage.setItem('name', 'Taro') when you click one button, and loads and displays the saved value with localStorage.getItem('name') using a different button. Try it and confirm for yourself that the saved value survives even after reloading the page.

A common beginner stumbling block is that localStorage can only store strings. If you want to save a number or an object, you first need to convert it into a string with JSON.stringify() before saving it, and turn it back into its original form with JSON.parse() when retrieving it.

Its distinguishing feature is being able to keep settings or notes using only the user's browser, without sending any data to a server. It's also often used behind the scenes of familiar website features, like remembering whether dark mode was selected.

HTML & CSS
OUTPUT

💡 The preview runs entirely on this page — nothing is sent externally.

", "sampleOutput": "", "goal": "Save data with localStorage.setItem() and read it back with getItem().", "note": "localStorage stores data in the browser. It survives closing the page, so the same data is still there on the next visit."}, "advanced": {"starter": "\n

\n", "sampleOutput": "", "goal": "Write a program that saves to localStorage when a button is clicked and shows the stored value on screen.", "note": "addEventListener(\"click\", ...) lets a button press trigger both the save to localStorage and the update to the display."}, "intermediate": {"goal": "Save to localStorage with one button and display the value with another."}}}
Ad space (banner)
Ad space (in-article)