Frequently asked questions

How do you create a counter in JavaScript?

Declare a variable at zero, get a reference to the element showing it, and attach click handlers to two buttons that add or subtract one and then rewrite the element's text. That is roughly twenty lines and needs no library or framework.

How do I make a counter that remembers its value?

Write the value to localStorage on every change and read it back on load. Wrap both in try/catch, because localStorage throws rather than returning null in private windows and when a browser blocks site data, which would otherwise break the whole script.

How do I add an undo button to a counter?

Push the previous value onto an array before each change, and pop from it to undo. Cap the array length, around 100 entries, so a long session cannot grow it without limit. This is the most requested counter feature and takes about ten lines.

Why does my counter show NaN?

Something non-numeric reached the arithmetic, almost always an empty or invalid number input: Number("") is 0 but Number("abc") is NaN, and NaN spreads through every later calculation. Validate with Number.isFinite before adding, and fall back to a sensible default.

How do I make a website hit counter?

That is a different thing and it needs a server, because the total must be shared between visitors. A browser-only counter stores its value per device. Shared totals require a backend or a hosted counting service to hold the number centrally.

People also search for

Or just use the finished one

Everything described here, already built: step sizes, undo, limits, auto count and offline support.