Save a counter in localStorage in JavaScript
Intermediate · 4 min read
Refresh a page and every variable in your JavaScript starts again from scratch. Sometimes that's fine. But a theme choice, a half-filled form or a game score should still be there when the user comes back. Browsers give every site a small place to keep data like that, called localStorage, and it survives reloads and even restarting the browser.
In this tutorial you will build a "Count up" button whose count is saved in localStorage, so it's still there after a refresh. Along the way you'll meet the two surprises that catch everyone: storage only holds text, and a missing key gives null. You should have used addEventListener and know what try and catch do.
How localStorage works
localStorage stores pairs of keys and values, like a tiny dictionary that belongs to your site. There are four methods you'll use:
localStorage.setItem(key, value)saves a value under a key.localStorage.getItem(key)reads it back.localStorage.removeItem(key)deletes it.localStorage.clear()deletes everything your site stored.
The page has one button:
<button id="inc" type="button">Count up</button>
Here is the exercise. Try it yourself first, or read on and we will build it together.
16 A counter that survives a refresh
fairKeep a count in localStorage so it is still there after the page reloads.
Stuck? Three hints, smallest first
- 1. Storage holds strings only. A number goes in and a string comes out.
- 2.
getItemreturnsnullfor a key that was never set. - 3.
setItemcan throw: storage may be full, or blocked in private browsing.
Step 1: what goes in, and what comes out
console.log(localStorage.getItem('never-set')); // null
localStorage.setItem('demo', 42);
console.log(localStorage.getItem('demo')); // 42, as the string '42'
console.log(typeof localStorage.getItem('demo')); // string
console.log(localStorage.getItem('demo') === 42); // false
Two things to remember:
- A key that was never set gives
null, notundefined. - Storage only holds strings. The number 42 is turned into the text
'42'on the way in, so it comes back as text, and=== 42is false.
Step 2: read the count safely
The count might be missing (first visit), or something unexpected (an older version of your code saved something else, or someone edited it in the browser's developer tools). So read it carefully:
const KEY = 'gsh-counter';
function readCount() {
const raw = localStorage.getItem(KEY);
const n = Number(raw);
return Number.isInteger(n) && n >= 0 ? n : 0;
}
console.log(readCount()); // 0: nothing stored yet
localStorage.setItem(KEY, 'not a number');
console.log(readCount()); // 0
localStorage.setItem(KEY, '7');
console.log(readCount()); // 7
Number() turns the text into a number. Then the check accepts only whole numbers that aren't negative, and anything else counts as 0.
Why so careful? Look what happens without the check:
console.log(Number(null)); // 0
console.log(Number('abc') + 1); // NaN
Number(null) happens to be 0, so a missing key works by luck. But Number('abc') is NaN ("not a number"), and NaN + 1 is still NaN. Your counter would save 'NaN' and stay broken forever.
Step 3: save the new count
function increment() {
try {
localStorage.setItem(KEY, String(readCount() + 1));
return { ok: true, count: readCount() };
} catch (error) {
return { ok: false, why: error.name };
}
}
localStorage.removeItem(KEY);
console.log(increment()); // { ok: true, count: 1 }
String(...) makes the conversion to text explicit, so anyone reading the code can see it happens.
The try and catch are there because setItem can throw an error. Storage space is limited, and when it's full, the browser throws an error called QuotaExceededError. Some browsers have also refused storage entirely in private browsing. Without catch, that error would stop the rest of your click handler. With it, increment reports what went wrong and the page carries on.
Step 4: connect the button
const button = document.getElementById('inc');
button.addEventListener('click', increment);
for (let i = 0; i < 3; i++) button.dispatchEvent(new Event('click'));
console.log(readCount()); // 4
console.log(localStorage.getItem(KEY)); // the string '4'
Step 3 already counted to 1, so three clicks take it to 4. If you reload the page now, readCount() still gives 4, because the value lives in the browser, not in a variable.
To start over, remove the key:
localStorage.removeItem(KEY);
console.log(readCount()); // 0
The full solution
The full solution can't use a real browser's storage, so it uses a small stand-in with the same methods. It keeps the two behaviors that matter: values become strings, and a missing key gives null. It can also be told to refuse the next write, the way a full store does. Its checks confirm a missing key is null, the counter starts at 0, three clicks give the string '3', rubbish, negative and decimal values fall back to 0, a refused write is reported instead of thrown, and removeItem clears it. Press Run, then click the live demo and reload its frame.
allow-scripts only, so it cannot reach this page.const KEY = 'gsh-counter';
// Read defensively: the value may be missing, or left over from an older version
// of the code, or edited by hand in devtools.
function readCount() {
const raw = localStorage.getItem(KEY); // null if never set
const n = Number(raw);
return Number.isInteger(n) && n >= 0 ? n : 0;
}
function increment() {
try {
localStorage.setItem(KEY, String(readCount() + 1)); // String(), explicitly
return { ok: true, count: readCount() };
} catch (error) {
// Full, or private browsing with storage blocked. Do not let this crash the page.
return { ok: false, why: error.name };
}
}
const button = el('button', { id: 'inc', type: 'button' }, 'Count up');
document.body.appendChild(button);
button.addEventListener('click', increment);
console.log('before anything is stored:', JSON.stringify(localStorage.getItem(KEY)), '<- null');
console.log('so the count reads :', readCount());
fire(button, 'click');
fire(button, 'click');
fire(button, 'click');
console.log('after three clicks :', readCount());
console.log('what is actually stored :', JSON.stringify(localStorage.getItem(KEY)), 'a', typeof localStorage.getItem(KEY));
// A number goes in, a string comes out.
localStorage.setItem('demo', 42);
console.log('stored the number 42, got:', JSON.stringify(localStorage.getItem('demo')));
// Rubbish in the key does not break the counter.
localStorage.setItem(KEY, 'not a number');
console.log('with rubbish stored :', readCount(), '<- falls back to 0');
// A full or blocked store.
localStorage.setItem(KEY, '3');
localStorage.failNextWith(new DOMException_('quota exceeded', 'QuotaExceededError'));
const failed = increment();
console.log('when the store refuses :', failed);
console.log('the count is unchanged :', readCount());
Output
16 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 16 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a missing key reads as null', localStorage.getItem('never-set'), null);
test('not as undefined', localStorage.getItem('never-set') === undefined, false);
test('and JSON.parse(null) is null, not a crash', JSON.parse(localStorage.getItem('never-set')), null);
test('the counter starts at 0 with nothing stored', (() => { localStorage.removeItem(KEY); return readCount(); })(), 0);
test('clicking increments it', (() => { fire(button, 'click'); return readCount(); })(), 1);
test('three clicks give 3', (() => { fire(button, 'click'); fire(button, 'click'); return readCount(); })(), 3);
test('the stored value is a string', typeof localStorage.getItem(KEY), 'string');
test('specifically "3"', localStorage.getItem(KEY), '3');
test('a stored number comes back as a string', (() => { localStorage.setItem('demo', 42); return localStorage.getItem('demo'); })(), '42');
test('so === against a number fails', localStorage.getItem('demo') === 42, false);
test('rubbish falls back to 0 instead of NaN', (() => { localStorage.setItem(KEY, 'abc'); return readCount(); })(), 0);
test('a negative stored value falls back too', (() => { localStorage.setItem(KEY, '-5'); return readCount(); })(), 0);
test('a decimal is refused as not an integer', (() => { localStorage.setItem(KEY, '2.5'); return readCount(); })(), 0);
test('a refused write is reported, not thrown', (() => { localStorage.setItem(KEY, '3'); localStorage.failNextWith(new DOMException_('full', 'QuotaExceededError')); return increment(); })(), { ok: false, why: 'QuotaExceededError' });
test('and the stored count is untouched', readCount(), 3);
test('removeItem clears it', (() => { localStorage.removeItem(KEY); return localStorage.getItem(KEY); })(), null);
Adapted: localStorage here is an in-memory stand-in with the same API, and it keeps the two behaviours that actually matter — strings only, and null for a missing key.
Storage stores strings. Put in 42 and you get back "42", so === 42 fails. Convert explicitly on the way in with String() and on the way out with Number(), and validate what comes out: a stored value can be missing, left over from an older version of your code, or edited by hand. readCount handles null, non-numbers, negatives and decimals, all asserted, and none of those are hypothetical for data that lives in the browser indefinitely.
The try/catch around setItem is not defensive clutter. Storage throws when the quota is exceeded, and Safari in private browsing has historically thrown on the very first write. An uncaught throw there takes down whatever else the handler was doing.
Common mistakes
- Forgetting that values are strings.
getItemgives'3', not3, so'3' + 1is'31'. Convert withNumber(). - Trusting what's stored. It can be missing, old or edited. Check it and fall back to a safe default.
- Calling
setItemwithouttry. It throws when storage is full or blocked, and the error stops your handler.
Try it yourself
- Add a "Reset" button that calls
localStorage.removeItem(KEY)and updates the display. - Add a "Count down" button that never goes below 0.
- Save the time of the last click with
new Date().toISOString()under a second key, and show it under the count.