Skip to content

Instantly share code, notes, and snippets.

@cmbaughman
Created May 29, 2026 13:32
Show Gist options
  • Select an option

  • Save cmbaughman/f4ceade2861aea3648b0a8d20552cd7e to your computer and use it in GitHub Desktop.

Select an option

Save cmbaughman/f4ceade2861aea3648b0a8d20552cd7e to your computer and use it in GitHub Desktop.
LocalStorage Sample Best Practices
// localStorage only writes strings
function setItem(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (e) {
if (e.name === "QuotaExceededError") {
console.warn("Local Storage quota exceeded! Please clear some old entries.");
}
}
}
// localStorage only stores strings not objects so parse!
function getItem(key, fallback = null) {
try {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) : fallback;
} catch {
return fallback;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment