Emmanuel Akinfulubi

JavaScriptBasic

Luhn algorithm: validate a card number in JavaScript

Advanced · 4 min read

When you type a card number on a checkout page and mistype one digit, the form often turns red before you even press Pay. It isn't asking the bank. It's running the Luhn check, a simple sum that every card number is built to pass. A single wrong digit breaks the sum, so the typo is caught on the spot.

In this tutorial you will write luhn(text), which checks a card number, and checkDigit(partial), which works out the last digit that makes a number valid. You'll also see the one kind of mistake Luhn can't catch. You need to know loops, arrays and the % remainder operator.

The Luhn rule

  1. Start from the rightmost digit.
  2. Leave the first digit alone, double the second, leave the third, double the fourth, and so on.
  3. If doubling gives more than 9, subtract 9.
  4. Add up all the digits.
  5. If the total divides evenly by 10, the number passes.

Why subtract 9? Doubling a digit gives at most 18. For a two-digit result, adding its digits gives the same answer as subtracting 9: 14 becomes 1 + 4 = 5, and 14 - 9 is also 5.

JavaScript

console.log(7 * 2);       // 14
console.log(1 + 4);       // 5
console.log(7 * 2 - 9);   // 5
console.log(70 % 10);     // 0: 70 divides evenly by 10

Why from the right?

Card numbers come in different lengths. Counting from the right means the doubling always starts in the same place relative to the last digit, which is the check digit. That's what lets one rule work for every length.

Here is the exercise. Try it on your own first if you like, or read on and we will build it together.

139 Does that card number pass the Luhn check

hard

Check a card number with the Luhn formula: from the right, double every second digit, subtract 9 from any result above 9, add everything up, and the total must divide by 10. Ignore spaces. Then compute the check digit that would make a partial number valid.

Stuck? Three hints, smallest first
  1. 1. Walk the digits from the right so the doubling starts in the same place whatever the length.
  2. 2. Doubling 7 gives 14, and 1 + 4 is 5, which is the same as 14 - 9.
  3. 3. For the check digit, the digit you are about to append shifts the doubling, so the parity flips.

Step 1: pull out the digits

People type spaces in card numbers. Keep only the digits, as numbers:

Step 1

const digitsOf = (text) => [...String(text)].filter((c) => c >= '0' && c <= '9').map(Number);
console.log(digitsOf('5060 9912')); // [ 5, 0, 6, 0, 9, 9, 1, 2 ]

[...String(text)] splits the text into characters. filter keeps the digit characters, and map(Number) turns each '5' into 5.

Step 2: walk from the right, doubling every second digit

Step 2

const digitsOf = (text) => [...String(text)].filter((c) => c >= '0' && c <= '9').map(Number);
function luhn(text) {
  const digits = digitsOf(text);
  if (digits.length < 2) return false;
  let sum = 0;
  for (let i = digits.length - 1, place = 0; i >= 0; i--, place++) {
    let d = digits[i];
    if (place % 2 === 1) {      // every second digit from the right
      d *= 2;
      if (d > 9) d -= 9;
    }
    sum += d;
  }
  return sum % 10 === 0;
}
console.log(luhn('5060 9912 3456 7895')); // true
console.log(luhn('5060 9912 3456 7894')); // false
console.log(luhn('79927398713'));         // true
console.log(luhn(''), luhn('5'));         // false false

The loop has two counters. i walks the array from the last index down to 0. place counts how far we are from the right: 0, 1, 2... Odd places get doubled.

A number needs at least two digits to have a check digit at all, so anything shorter fails straight away. Change just the last digit and the check fails, as the second line shows.

Step 3: work out the check digit

Card issuers choose the first digits, then add one final digit to make the Luhn sum come out right. To compute it, run the same sum over the partial number, with one difference: the new digit will sit at place 0 and push every other digit one place left. So now the even places get doubled.

Step 3

const digitsOf = (text) => [...String(text)].filter((c) => c >= '0' && c <= '9').map(Number);
function checkDigit(partial) {
  const digits = digitsOf(partial);
  let sum = 0;
  for (let i = digits.length - 1, place = 0; i >= 0; i--, place++) {
    let d = digits[i];
    if (place % 2 === 0) {
      d *= 2;
      if (d > 9) d -= 9;
    }
    sum += d;
  }
  return (10 - (sum % 10)) % 10;
}
console.log(checkDigit('506099123456789')); // 5
console.log(checkDigit('7992739871'));      // 3

10 - (sum % 10) is how much is needed to reach the next multiple of 10. The final % 10 handles the case where the sum already ends in 0: then we need 0, not 10.

Step 4: what Luhn catches, and what it misses

Luhn catches every single mistyped digit. It also catches most swaps of two neighboring digits. But not all of them:

Step 4

const digitsOf = (text) => [...String(text)].filter((c) => c >= '0' && c <= '9').map(Number);
function luhn(text) {
  const digits = digitsOf(text);
  if (digits.length < 2) return false;
  let sum = 0;
  for (let i = digits.length - 1, place = 0; i >= 0; i--, place++) {
    let d = digits[i];
    if (place % 2 === 1) {
      d *= 2;
      if (d > 9) d -= 9;
    }
    sum += d;
  }
  return sum % 10 === 0;
}
console.log(luhn('5060 9921 3456 7895')); // false: 1 and 2 swapped, caught
console.log(luhn('5069 0912 3456 7895')); // true: 0 and 9 swapped, missed

Swapping a 0 and a 9 slips through. Doubling 0 gives 0, and doubling 9 gives 18, which becomes 9. So whichever of the two is doubled, the pair adds up to 9 either way.

So treat Luhn as a typo filter. A pass means "the digits are consistent and worth sending". It says nothing about whether the card exists or has money on it. Only the bank knows that.

The full solution

The answer panel has digitsOf, luhn and checkDigit. It checks a sample card and computes the check digit for its first fifteen digits. The checks also try every possible single-digit typo in that card and confirm all of them are caught. Press Run to see the output.

The answer

const digitsOf = (text) => [...String(text)].filter((c) => c >= '0' && c <= '9').map(Number);

function luhn(text) {
  const digits = digitsOf(text);
  if (digits.length < 2) return false;
  let sum = 0;
  for (let i = digits.length - 1, place = 0; i >= 0; i--, place++) {
    let d = digits[i];
    if (place % 2 === 1) {              // every second digit from the right
      d *= 2;
      if (d > 9) d -= 9;                // 14 -> 5, the same as adding its digits
    }
    sum += d;
  }
  return sum % 10 === 0;
}

// The digit that would complete a number. The parity flips because the appended
// digit takes place 0 and pushes everything else along one.
function checkDigit(partial) {
  const digits = digitsOf(partial);
  let sum = 0;
  for (let i = digits.length - 1, place = 0; i >= 0; i--, place++) {
    let d = digits[i];
    if (place % 2 === 0) {
      d *= 2;
      if (d > 9) d -= 9;
    }
    sum += d;
  }
  return (10 - (sum % 10)) % 10;
}

const CARD = '5060 9912 3456 7895';
console.log(CARD, luhn(CARD) ? 'passes' : 'fails');
console.log('check digit for 506099123456789:', checkDigit('506099123456789'));

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('a valid number passes, spaces and all', luhn(CARD), true);
test('change the last digit and it fails', luhn('5060 9912 3456 7894'), false);
test('the textbook example passes too', luhn('79927398713'), true);
test('the check digit completes a partial number', [checkDigit('506099123456789'), luhn('506099123456789' + checkDigit('506099123456789'))], [5, true]);
test('subtracting 9 is the same as adding the digits of the double', [(7 * 2) - 9, 1 + 4], [5, 5]);
test('every single-digit typo in that card is caught', digitsOf(CARD).flatMap((d, i) => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].filter((n) => n !== d).map((n) => { const copy = digitsOf(CARD); copy[i] = n; return luhn(copy.join('')); })).filter(Boolean).length, 0);
test('and so is swapping most neighbouring pairs', luhn('5060 9921 3456 7895'), false);
test('but a 0 and a 9 swapped slips straight through', [luhn('5069 0912 3456 7895'), 0 * 2 - 0, 9 * 2 - 9], [true, 0, 9]);
test('too short to have a check digit at all', [luhn(''), luhn('5')], [false, false]);

Walking from the right is what makes the formula length-independent: a 16-digit Verve number and a 15-digit Amex have their doubled digits in different absolute positions but the same positions counted backwards. And d -= 9 is not a trick — doubling a digit can only reach 18, and for any two-digit result subtracting 9 equals summing its digits.

Luhn catches every single-digit mistake, which the sixth assertion checks exhaustively across all 16 positions and all 9 wrong digits. It also catches most transpositions of neighbours, but not all: the pair 0 and 9 is invisible to it, because doubling 0 contributes 0 either way and doubling 9 gives 18 which folds back to 9. The eighth assertion swaps a 0 and a 9 and the number still passes.

So Luhn is a typo filter, not a validity check. It tells you the digits are internally consistent, which is worth doing in the browser before a payment request goes anywhere. It tells you nothing about whether the card exists, has money on it, or belongs to the person typing — only the issuer knows that. Treat a pass as "worth sending" and never as "accepted".

Common mistakes

  • Doubling from the left. For numbers with an odd number of digits, the wrong digits get doubled.
  • Forgetting to remove spaces. A space isn't a digit, so filter the text first.
  • Treating a pass as a real card. Luhn only catches typos. The payment still has to be checked by the bank.

Try it yourself

  1. Write formatCard(text) that groups the digits in fours with spaces, like 5060 9912 3456 7895.
  2. Write a function that makes a random 16-digit test number that passes: 15 random digits, then checkDigit.
  3. Count how many of the 15 swaps of neighboring digits in the sample card Luhn catches.

Keep practising

Newsletter

New writing, when it lands.

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