← 講座に戻る: JavaScript from scratch

localStorage and week 7 review

動画は近日公開

If you reload a page, all JavaScript variables disappear: the program's memory lives only while the page is open. For data to survive you need a place to store it. The browser offers localStorage, a small store of key-value pairs that persists even if you close the tab or turn off the computer. It is perfect for preferences, drafts or a task list, and it needs no server.

The localStorage API

It has four basic operations: setItem(key, value) saves, getItem(key) reads (it returns null if it does not exist), removeItem(key) deletes one entry and clear() deletes everything. There is an essential limitation: it only stores strings. If you save a number, it comes back as text; if you save an object without converting it, you get the string '[object Object]'. For complex structures use JSON.stringify when saving and JSON.parse when reading, which you learned in week 6.

javascript
localStorage.setItem('theme', 'dark');
console.log(localStorage.getItem('theme'));   // dark
console.log(localStorage.getItem('missing')); // null

localStorage.setItem('visits', 5);
console.log(typeof localStorage.getItem('visits')); // string
console.log(Number(localStorage.getItem('visits')) + 1); // 6

const tasks = [{ id: 1, text: 'Study', done: false }];
localStorage.setItem('tasks', JSON.stringify(tasks));

const saved = JSON.parse(localStorage.getItem('tasks')) ?? [];
console.log(saved[0].text); // Study

localStorage.removeItem('theme');

A safe pattern to load and save

Stored data can be corrupted, edited by hand or not exist yet. That is why reading must be protected: use try...catch around JSON.parse and return a default value if something fails. Write two small functions, loadData and saveData, and use them throughout the application; that way the rest of the code does not worry about the details. Also keep the limits in mind: about 5 MB per origin, data visible to anyone using that browser and readable by other scripts of your own site. Never store passwords or sensitive data here.

javascript
const STORAGE_KEY = 'my-app-data';

function loadData(fallback = []) {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    return raw === null ? fallback : JSON.parse(raw);
  } catch {
    return fallback; // corrupted data: start clean
  }
}

function saveData(data) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
}

const items = loadData();
items.push({ id: Date.now(), text: 'New item' });
saveData(items);
console.log(loadData().length);

Week 7 review

  • The DOM is the page tree; document.querySelector selects elements.
  • textContent changes text safely; innerHTML with user data is an XSS risk.
  • addEventListener connects events with functions; event.preventDefault() cancels the default action.
  • Event delegation uses a single handler on the parent.
  • localStorage stores strings; use JSON.stringify and JSON.parse for objects.

sessionStorage and other options

There is a sibling of localStorage called sessionStorage, with the same API but whose data is deleted when the tab is closed; it is used for temporary states, such as the current step of a wizard. For larger or structured data there is IndexedDB, and to keep information between the browser and a server cookies or remote databases are used. As long as your application is small and personal, localStorage is enough. Remember that the user can clear it whenever they want, so do not treat it as a reliable database: it is a convenience, not a backup.

理解度チェック

問題 1 / 7

Which method returns the first element matching a CSS selector?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →