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
Enter fullscreen mode
Exit fullscreen mode
So the full code is 4006381333931 .
In JavaScript
function ean13Check ( first12 ) { const sum = [ . . . first12 ] . reduce ( ( acc , d , i ) => acc + Number ( d ) * ( i % 2 ?β¦