Emmanuel Akinfulubi

JavaScriptMath

Check digit algorithms (Luhn, NUBAN) in JavaScript

Advanced · 5 min read

Card numbers, bank account numbers and book ISBNs all end with a check digit: one extra digit worked out from all the others. If someone mistypes a digit, the check usually fails, and the form can reject the number before anything is sent. It is the reason a payment page can say "this card number isn't valid" the moment you finish typing.

In this tutorial you will build three real check-digit schemes: Luhn for card numbers, the 3-7-3 weighted sum used for Nigerian NUBAN account numbers, and the mod 11 check in ISBN-10. Then you will test each one against every possible typo of two common kinds and find exactly which mistakes each scheme can't see. A plain digit sum goes first, as the control. You need to know strings, loops and %.

Two kinds of typo

Check digits are usually judged on two kinds of typo:

  • A single-digit error: one digit is wrong, like 4111 typed as 4711.
  • An adjacent swap: two neighbors trade places, like 12 typed as 21.

A good check digit should catch both. The way to know is to test every case, not a few examples.

Weights

Most schemes multiply each digit by a weight before adding them up, and the weight depends on the digit's position. Without weights, swapping two digits can't change the total, because addition doesn't care about order.

JavaScript

const digits = (s) => [...s].map(Number);
console.log(digits('4091')); // [ 4, 0, 9, 1 ]

digits turns a string into an array of numbers, and every scheme below starts with it.

Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.

114 Check digits, and the errors each one cannot see

hard

Implement three check-digit schemes: Luhn for card numbers, the 3-7-3 weighted sum Nigerian NUBAN account numbers use, and ISBN-10's mod 11. For each, exhaustively test every single-digit error and every swap of two adjacent digits, and report which errors each scheme cannot detect. Add a plain digit-sum check as the control.

Stuck? Three hints, smallest first
  1. 1. Luhn doubles every second digit from the right and subtracts 9 if the doubling passes 9; a valid number has a total divisible by 10.
  2. 2. A weighted scheme cannot see a swap of two digits whose weights are equal, because the weighted sum does not change.
  3. 3. Mod 11 with weights 10, 9, 8, ... 1 gives every position a distinct weight and a prime modulus, which is why it needs an X.

Step 1: the control, a plain digit sum

Step 1

const sumDigit = (body) => (10 - (digits(body).reduce((a, b) => a + b, 0) % 10)) % 10;
const sumValid = (s) => sumDigit(s.slice(0, -1)) === Number(s[s.length - 1]);
console.log(sumDigit('123'), sumValid('1234'), sumValid('2134')); // 4 true true

The check digit tops the total up to a multiple of 10. The last % 10 turns a top-up of 10 into 0. It catches a single wrong digit, but 2134 passes too: a swap never changes a plain sum.

Step 2: Luhn

Luhn doubles every second digit, counting from the right, and subtracts 9 from any result above 9. A valid number has a total that divides by 10.

Step 2

function luhnTotal(s) {
  const d = digits(s);
  let total = 0;
  for (let i = 0; i < d.length; i++) {
    const fromRight = d.length - 1 - i;
    let v = d[i];
    if (fromRight % 2 === 1) {
      v *= 2;
      if (v > 9) v -= 9;
    }
    total += v;
  }
  return total;
}
const luhnValid = (s) => luhnTotal(s) % 10 === 0;
const luhnDigit = (body) => (10 - (luhnTotal(body + '0') % 10)) % 10;
console.log(luhnValid('79927398713'), luhnTotal('79927398713')); // true 70
console.log(luhnValid('4111111111111111'), luhnDigit('411111111111111')); // true 1

fromRight is the position counted from the right, starting at 0, so the check digit is never doubled. To make a check digit, luhnDigit adds a placeholder '0' so the doubling lines up, then tops up to a multiple of 10.

Step 3: every single-digit error

Step 3

const card = '4111111111111111';
let missedSingle = 0;
for (let i = 0; i < card.length; i++) {
  for (let d = 0; d <= 9; d++) {
    if (String(d) === card[i]) continue;
    if (luhnValid(card.slice(0, i) + d + card.slice(i + 1))) missedSingle++;
  }
}
console.log(missedSingle, card.length * 9); // 0 144

16 positions, each with 9 wrong digits, is 144 typos. slice rebuilds the string with one digit replaced. Luhn catches all 144.

Step 4: every adjacent swap

Step 4

function missedSwaps(check, valid) {
  const missed = [];
  for (let a = 0; a <= 9; a++) {
    for (let b = 0; b <= 9; b++) {
      if (a === b) continue;
      const body = '0306' + a + b + '15';
      const full = body + check(body);
      const swapped = full.slice(0, 4) + b + a + full.slice(6);
      if (valid(swapped)) missed.push(a + '' + b);
    }
  }
  return missed;
}
console.log(missedSwaps(luhnDigit, luhnValid));     // [ '09', '90' ]
console.log(missedSwaps(sumDigit, sumValid).length); // 90

The function tries all 90 ordered pairs of different digits, builds a valid number with the pair in positions 4 and 5, swaps them, and records each swap the check fails to notice. You pass in the scheme's two functions, so one test works for every scheme.

The plain sum misses all 90. Luhn misses only two: 09 and 90. Doubled, 0 stays 0, and 9 becomes 18, which folds to 9. Either way round, the pair adds 9 to the total. That is the one famous gap in the scheme used for most card numbers.

Step 5: ISBN-10 and mod 11

ISBN-10 gives every position its own weight, 10 down to 1, and works mod 11. A check value of 10 is written as X.

Step 5

function isbnDigit(body) {
  const total = digits(body).reduce((sum, v, i) => sum + v * (10 - i), 0);
  const check = (11 - (total % 11)) % 11;
  return check === 10 ? 'X' : String(check);
}
const isbnValid = (s) =>
  [...s].map((c) => (c === 'X' ? 10 : Number(c))).reduce((sum, v, i) => sum + v * (10 - i), 0) % 11 === 0;
console.log(isbnDigit('030640615'), isbnDigit('043942089'), isbnValid('097522980X')); // 2 X true

reduce passes the position i as its third argument, so the weight is 10 - i.

Step 6: ISBN catches every swap

Step 6

let isbnMissed = 0;
for (let a = 0; a <= 9; a++) {
  for (let b = 0; b <= 9; b++) {
    if (a === b) continue;
    const body = '0306' + a + b + '150';
    const full = body + isbnDigit(body);
    const swapped = full.slice(0, 4) + b + a + full.slice(6);
    if (!isbnValid(full) || isbnValid(swapped)) isbnMissed++;
  }
}
console.log(isbnMissed); // 0

This is the same swap test, with a nine-digit body so the check digit lands in position ten with weight 1, as a real ISBN-10 needs. It also counts any number that wasn't valid to begin with, so a 0 means every one of the 90 was valid before the swap and caught after. Neighbors always have different weights, and 11 is prime, so a swap always changes the total by something 11 can't divide.

Step 7: NUBAN and repeated weights

A NUBAN account number weights the bank code and the 9-digit serial with 3, 7, 3 repeating, then adds a check digit to make 10 digits.

Step 7

const WEIGHTS = [3, 7, 3, 3, 7, 3, 3, 7, 3, 3, 7, 3];
function nubanDigit(bank, serial) {
  const d = digits(bank + serial);
  const total = d.reduce((sum, v, i) => sum + v * WEIGHTS[i], 0);
  return (10 - (total % 10)) % 10;
}
const bank = '011';
const serial = '123456789';
console.log(serial + nubanDigit(bank, serial)); // 1234567895
const nubanSwaps = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => {
  const swapped = serial.slice(0, i) + serial[i + 1] + serial[i] + serial.slice(i + 2);
  return nubanDigit(bank, swapped) !== nubanDigit(bank, serial);
});
console.log(nubanSwaps.join(' ')); // true true false true true false true true

nubanSwaps swaps each pair of neighbors in the serial and asks whether the check digit changes. Two swaps go unseen. Both sit where the pattern repeats a 3 next to a 3. Two digits with the same weight can trade places and the total stays the same.

The full solution

The answer panel has all four schemes, the single-digit and swap tests, and the NUBAN check, and confirms that the unseen NUBAN swaps are exactly where WEIGHTS[i] === WEIGHTS[i + 1]. Press Run to see the output.

The answer

const digits = (s) => [...s].map(Number);

// Luhn: double every second digit counting from the right.
function luhnTotal(s) {
  const d = digits(s);
  let total = 0;
  for (let i = 0; i < d.length; i++) {
    const fromRight = d.length - 1 - i;
    let v = d[i];
    if (fromRight % 2 === 1) {
      v *= 2;
      if (v > 9) v -= 9;
    }
    total += v;
  }
  return total;
}
const luhnValid = (s) => luhnTotal(s) % 10 === 0;
const luhnDigit = (body) => (10 - (luhnTotal(body + '0') % 10)) % 10;

// NUBAN: weights 3, 7, 3 repeating over the bank code and the serial number.
const WEIGHTS = [3, 7, 3, 3, 7, 3, 3, 7, 3, 3, 7, 3];
function nubanDigit(bank, serial) {
  const d = digits(bank + serial);
  const total = d.reduce((sum, v, i) => sum + v * WEIGHTS[i], 0);
  return (10 - (total % 10)) % 10;
}

// ISBN-10: weights 10 down to 1, modulus 11, and a check value of 10 prints as X.
function isbnDigit(body) {
  const total = digits(body).reduce((sum, v, i) => sum + v * (10 - i), 0);
  const check = (11 - (total % 11)) % 11;
  return check === 10 ? 'X' : String(check);
}
const isbnValid = (s) =>
  [...s].map((c) => (c === 'X' ? 10 : Number(c))).reduce((sum, v, i) => sum + v * (10 - i), 0) % 11 === 0;

// The control: add the digits, no weights at all.
const sumDigit = (body) => (10 - (digits(body).reduce((a, b) => a + b, 0) % 10)) % 10;
const sumValid = (s) => sumDigit(s.slice(0, -1)) === Number(s[s.length - 1]);

const card = '4111111111111111';

// Every single-digit change to the card: 16 positions, 9 wrong digits each.
let missedSingle = 0;
for (let i = 0; i < card.length; i++) {
  for (let d = 0; d <= 9; d++) {
    if (String(d) === card[i]) continue;
    if (luhnValid(card.slice(0, i) + d + card.slice(i + 1))) missedSingle++;
  }
}

// Every ordered pair of distinct digits, swapped in the same two positions.
function missedSwaps(check, valid) {
  const missed = [];
  for (let a = 0; a <= 9; a++) {
    for (let b = 0; b <= 9; b++) {
      if (a === b) continue;
      const body = '0306' + a + b + '15';
      const full = body + check(body);
      const swapped = full.slice(0, 4) + b + a + full.slice(6);
      if (valid(swapped)) missed.push(a + '' + b);
    }
  }
  return missed;
}

const bank = '011';
const serial = '123456789';
const account = serial + nubanDigit(bank, serial);
// Which adjacent swaps inside the serial does NUBAN see? Only those across
// positions whose weights differ.
const nubanSwaps = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => {
  const swapped = serial.slice(0, i) + serial[i + 1] + serial[i] + serial.slice(i + 2);
  return nubanDigit(bank, swapped) !== nubanDigit(bank, serial);
});

console.log('luhn 79927398713 :', luhnValid('79927398713'), 'total', luhnTotal('79927398713'));
console.log('luhn test card   :', luhnValid(card), 'check digit for 411111111111111 is', luhnDigit('411111111111111'));
console.log('single-digit miss:', missedSingle, 'of', card.length * 9);
console.log('luhn swaps missed:', missedSwaps(luhnDigit, luhnValid));
console.log('isbn swaps missed:', missedSwaps(isbnDigit, isbnValid));
console.log('sum swaps missed :', missedSwaps(sumDigit, sumValid).length, 'of 90');
console.log('nuban account    :', account, 'from bank', bank, 'and serial', serial);
console.log('nuban swaps seen :', nubanSwaps, 'weights', WEIGHTS.slice(3));
console.log('isbn             :', isbnDigit('030640615'), isbnDigit('043942089'), isbnValid('097522980X'));

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('two published Luhn examples check out, and the algorithm reproduces the digit', [luhnValid('79927398713'), luhnValid(card), luhnDigit('411111111111111')], [true, true, 1]);
test('Luhn catches all 144 single-digit errors in a 16-digit number', [missedSingle, card.length * 9], [0, 144]);
test('but of the 90 ordered pairs, it cannot see 0 swapped with 9', missedSwaps(luhnDigit, luhnValid), ['09', '90']);
test('mod 11 with distinct weights misses none of the 90', missedSwaps(isbnDigit, isbnValid), []);
test('while a plain digit sum misses every single one of them', missedSwaps(sumDigit, sumValid).length, 90);
test('ISBN-10 needs an X when the check value comes out as 10', [isbnDigit('030640615'), isbnDigit('043942089'), isbnValid('097522980X')], ['2', 'X', true]);
test('the NUBAN scheme turns a 9-digit serial into a 10-digit account number', [account, account.length], ['1234567895', 10]);
test('and its 3, 7, 3 weights are blind to a swap wherever two neighbours share a weight', nubanSwaps, [true, true, false, true, true, false, true, true]);
test('which is exactly where the weight list repeats itself', [0, 1, 2, 3, 4, 5, 6, 7].map((i) => WEIGHTS[i + 3] !== WEIGHTS[i + 4]), nubanSwaps);

A check digit is one number's worth of redundancy, and what it buys you depends entirely on the weights. The control at the bottom makes that concrete: a plain digit sum catches every single-digit error and none of the 90 adjacent swaps, because reordering the digits does not change their sum. Luhn's alternate doubling fixes that for 88 of the 90 — the two it misses are 09 and 90, since doubling 0 gives 0 and doubling 9 gives 18 which folds to 9, so the pair contributes 9 either way. That is the one famous hole in the scheme that guards most of the world's card numbers.

The NUBAN weights show the general rule. Any weighted sum is blind to a swap of two digits whose weights are equal, because the total is unchanged — and 3, 7, 3, 3, 7, 3 has adjacent equal weights wherever the pattern wraps. The last two assertions test exactly that: the positions NUBAN cannot see a swap in are precisely the positions where WEIGHTS[i] === WEIGHTS[i + 1], computed two independent ways and compared. It still catches every single-digit error, which is the common case, and a 10-digit account number that fails the check can be rejected before it reaches an interbank transfer.

ISBN-10 is the one with the cleanest mathematics: weights 10 down to 1 are all distinct, and the modulus 11 is prime, so every single-digit error and every transposition — adjacent or not — changes the total. The price is that the check value can come out as 10, which does not fit in a digit, hence the X. That is the trade: a prime modulus gives you complete transposition detection and an alphabet you did not want. When you design one of these, decide first which errors your users actually make.

Common mistakes

  • Counting Luhn positions from the left. The doubling starts from the right, so numbers of different lengths still line up.
  • Forgetting the X in ISBN-10. A check value of 10 doesn't fit in one digit, so it is written as X.
  • Testing a check with a few examples. Loop over every typo, as here, and you find the gaps for certain.

Try it yourself

  1. Use luhnDigit to finish the card number 453201511283036.
  2. Count how many of the 144 single-digit errors the plain digit sum misses on the test card.
  3. Change one 3 in WEIGHTS so no two neighbors are equal, and run nubanSwaps again.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.