On this page11 sections
  1. Learning Objectives
  2. 1. Saving and Reading
  3. 2. The Methods
  4. 3. A Click Counter That Survives Refreshes
  5. 4. Objects and Arrays: Use JSON
  6. 5. sessionStorage
  7. 6. What Not to Store
  8. Common Beginner Mistakes
  9. Practice Questions
  10. Practice Answers
  11. Key Takeaways

Lecture 046: Web Storage API

Category8: Web APIs
Lecture046 of 048
Estimated video length12 min
TargetHTML5 · any modern browser
LevelBeginner

Web Storage lets a page remember small things in the visitor's browser: their dark-mode choice, a draft message, items in a cart. localStorage keeps data until it's deleted; sessionStorage forgets it when the tab closes.


Learning Objectives

  • Save, read and delete values with localStorage
  • Know when to use sessionStorage instead
  • 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.html and open it in your browser. Then refresh the page and watch the data survive.


1. Saving and Reading

html
<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

MethodDoes
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) / lengthLoops over what's stored

3. A Click Counter That Survives Refreshes

html
<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

html
<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.

html
<script>
  sessionStorage.setItem('step', '2');
  sessionStorage.getItem('step');   // "2", until the tab is closed
</script>
localStoragesessionStorage
LastsUntil deletedUntil the tab closes
Shared between tabsYesNo
Typical size limitAbout 5 MBAbout 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

  1. What's the difference between localStorage and sessionStorage?
  2. Save the value dark under the key theme.
  3. What does getItem return if nothing was saved?
  4. How do you store an array?
  5. Why shouldn't you store passwords in localStorage?
  6. Where can you see a site's stored data?

Practice Answers

  1. localStorage keeps data until it's deleted; sessionStorage clears when the tab closes.
  2. localStorage.setItem('theme', 'dark');
  3. null
  4. localStorage.setItem('list', JSON.stringify(array)); and read it back with JSON.parse.
  5. Any JavaScript on the page can read it, so it isn't secure.
  6. DevTools → Application → Local Storage.

Key Takeaways

  • localStorage remembers small values across visits; sessionStorage per tab.
  • setItem, getItem, removeItem, clear.
  • Values are strings: use Number() and JSON.stringify / JSON.parse.
  • Never store secrets.