On this page11 sections
Lecture 046: Web Storage API
| Category | 8: Web APIs |
| Lecture | 046 of 048 |
| Estimated video length | 12 min |
| Target | HTML5 · any modern browser |
| Level | Beginner |
Web Storage lets a page remember small things in the visitor's browser: their dark-mode choice, a draft message, items in a cart.
localStoragekeeps data until it's deleted;sessionStorageforgets it when the tab closes.
Learning Objectives
- Save, read and delete values with
localStorage - Know when to use
sessionStorageinstead - Store objects and arrays with JSON
- Know what not to store
Storage is blocked inside this page's sandboxed preview boxes, so these examples have no Run button. Copy each one into a file such as
storage.htmland open it in your browser. Then refresh the page and watch the data survive.
1. Saving and Reading
<input id="name" placeholder="Your name">
<button type="button" onclick="save()">Save</button>
<p id="hello"></p>
<script>
function save() {
localStorage.setItem('name', document.getElementById('name').value);
greet();
}
function greet() {
const name = localStorage.getItem('name'); // null if nothing saved
document.getElementById('hello').textContent = name ? `Welcome back, ${name}!` : 'Hello, stranger.';
}
greet();
</script>Type your name, save, then refresh. The page still knows you.
2. The Methods
| Method | Does |
|---|---|
setItem(key, value) | Saves a value |
getItem(key) | Reads it (null if missing) |
removeItem(key) | Deletes one value |
clear() | Deletes everything for this site |
key(i) / length | Loops over what's stored |
3. A Click Counter That Survives Refreshes
<button type="button" onclick="count()">Click me</button>
<p id="out"></p>
<script>
function show() {
document.getElementById('out').textContent = `Clicked ${localStorage.getItem('clicks') || 0} times (ever).`;
}
function count() {
const clicks = Number(localStorage.getItem('clicks') || 0) + 1;
localStorage.setItem('clicks', clicks);
show();
}
show();
</script>Storage only holds strings, so numbers come back as text. Convert them with Number().
4. Objects and Arrays: Use JSON
<script>
const cart = [{ item: 'Kurta', qty: 1 }, { item: 'Shawl', qty: 2 }];
localStorage.setItem('cart', JSON.stringify(cart)); // object → text
const saved = JSON.parse(localStorage.getItem('cart') || '[]'); // text → object
console.log(saved[1].item); // "Shawl"
</script>5. sessionStorage
The same methods, but data lasts only while the tab is open, which suits a multi-step form.
<script>
sessionStorage.setItem('step', '2');
sessionStorage.getItem('step'); // "2", until the tab is closed
</script>localStorage | sessionStorage | |
|---|---|---|
| Lasts | Until deleted | Until the tab closes |
| Shared between tabs | Yes | No |
| Typical size limit | About 5 MB | About 5 MB |
6. What Not to Store
- Passwords, tokens or personal data. Any script on the page can read storage.
- Large data. Use a proper database (the IndexedDB API) for big amounts.
You can see what a site stores in DevTools → Application → Local Storage.
Common Beginner Mistakes
1. Storing objects directly. setItem('cart', cart) saves "[object Object]". Use JSON.stringify.
2. Forgetting values are strings. '1' + 1 is '11'. Convert with Number().
3. Not checking for null. getItem returns null the first time. Provide a default with || ….
Practice Questions
- What's the difference between
localStorageandsessionStorage? - Save the value
darkunder the keytheme. - What does
getItemreturn if nothing was saved? - How do you store an array?
- Why shouldn't you store passwords in
localStorage? - Where can you see a site's stored data?
Practice Answers
localStoragekeeps data until it's deleted;sessionStorageclears when the tab closes.localStorage.setItem('theme', 'dark');nulllocalStorage.setItem('list', JSON.stringify(array));and read it back withJSON.parse.- Any JavaScript on the page can read it, so it isn't secure.
- DevTools → Application → Local Storage.
Key Takeaways
localStorageremembers small values across visits;sessionStorageper tab.setItem,getItem,removeItem,clear.- Values are strings: use
Number()andJSON.stringify/JSON.parse. - Never store secrets.