Every EAN-13 and UPC-A barcode ends in a digit that isn't data at all. It's a check digit, and it lets a scanner (or your code) reject most typos instantly.
The EAN-13 rule
Take the first 12 digits. Multiply them alternately by 1 and 3, starting with 1 from the left. Add it all up. The check digit is whatever brings the total up to the next multiple of 10.
Example: 400638133393?
digits: 4 0 0 6 3 8 1 3 3 3 9 3
weights: 1 3 1 3 1 3 1 3 1 3 1 3
sum = 4+0+0+18+3+24+1+9+3+9+9+9 = 89
check = (10 - 89 % 10) % 10 = 1
So the full code is 4006381333931.
In JavaScript
function ean13Check(first12) {
const sum = [...first12].reduce(
(acc, d, i) => acc + Number(d) * (i % 2 ? 3 : 1), 0);
return (10 - (sum % 10)) % 10;
}
UPC-A uses the same idea on 11 digits, but the weights start with 3 instead of 1.
What it catches (and doesn't)
- Any single wrong digit: always caught.
- Most swaps of two neighbouring digits: caught, except when the two digits differ by 5 (e.g. 0↔5, 2↔7), because 3×5 = 15 ends in 5 either way.
- Other systems trade complexity for strength: ISBN-10 uses mod 11 (catches all adjacent swaps), and credit cards use the Luhn algorithm.
Try it
Disclosure: I run GoToolsOnline. Its free barcode generator computes and validates the check digit for EAN-13/UPC-A and other formats as you type: https://gotoolsonline.com/tools/barcode-generator
Top comments (0)