Master the Luhn Algorithm: Definition, Examples, and TypeScript Implementation
Learn what the Luhn (mod‑10) algorithm is, its real‑world applications such as credit‑card and IMEI validation, step‑by‑step calculation examples, and see practical TypeScript and JavaScript implementations that you can integrate into your web projects.
What is the Luhn Algorithm? (Definition)
Luhn algorithm (also called “mod‑10 algorithm”) is a simple yet practical checksum algorithm commonly used to validate credit‑card numbers, ID numbers, IMEI codes and other numeric strings. It was introduced by IBM scientist Hans Peter Luhn in 1954.
The principle is to compute a control digit (checksum) from a sequence of numbers, allowing verification of the number’s correctness because the checksum depends on the other digits.
In simple terms, each digit of the numeric string is weighted, transformed, summed, and the result is checked for divisibility by 10.
Typical use cases include:
Credit‑card number validation
ID number checksum verification (in some countries)
IMEI mobile‑device number validation
Membership or order number checksum generation
Bank‑card number front‑end validation
Example:
<code>12345674 is a valid card number,
1234567 is the base number and 4 is the check digit.</code>The Luhn algorithm can quickly detect input errors, typos, or invalid numbers before processing critical operations such as credit‑card payments.
<code>If a user enters 13245674 (2 and 3 swapped),
the program computes the Luhn checksum for 1324567, obtaining 5 instead of the expected 4,
so the number is invalid, indicating an input mistake.</code>How to validate a number with the Luhn algorithm? (Validity check)
The algorithm processes the number from right to left, doubling every second digit. If doubling yields a number ≥ 10, replace it with the sum of its digits. Sum all digits to obtain s . The check digit c is calculated as:
<code>c = (10 - (s mod 10)) mod 10</code>Example:
Assume the number is 853X, where X = 0 is the digit to be calculated.
Take digit 3, double it → 6.
Take digit 5, leave unchanged.
Take digit 8, double → 16, then 1 + 6 = 7.
Sum: 6 + 5 + 7 = 18. Since 18 mod 10 = 8, compute (10 – 8) % 10 = 2, which is the check digit. Thus 8532 is valid under Luhn.
How to generate a valid number?
Choose a base number, compute its Luhn check digit (or use a generator), and append the digit to the end.
TypeScript implementation
Now that the algorithm is understood, here is a TypeScript version:
<code>function luhnCheck(cardNumber: string): boolean {
const sanitized = cardNumber.replace(/\D/g, '');
let sum = 0;
let shouldDouble = false;
for (let i = sanitized.length - 1; i >= 0; i--) {
let digit = parseInt(sanitized.charAt(i), 10);
if (shouldDouble) {
digit *= 2;
if (digit > 9) {
digit -= 9;
}
}
sum += digit;
shouldDouble = !shouldDouble;
}
return sum % 10 === 0;
}
const cardNumber = '4539 1488 0343 6467';
console.log(luhnCheck(cardNumber) ? 'Valid' : 'Invalid');</code>JavaScript implementation
<code>const luhnCheck = num => {
const arr = `${num}`.split('').reverse().map(x => Number.parseInt(x));
const lastDigit = arr.shift();
let sum = arr.reduce((acc, val, i) =>
i % 2 !== 0 ? acc + val : acc + ((val *= 2) > 9 ? val - 9 : val), 0);
sum += lastDigit;
return sum % 10 === 0;
};
luhnCheck('4485275742308327');
luhnCheck(6011329933655299);
luhnCheck(123456789);
</code>The Luhn algorithm is a powerful yet simple method for validating numbers and catching errors. Implementing it in TypeScript or JavaScript ensures your web applications have an efficient and reliable validation mechanism.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.