DEV Community

Cover image for Luhn Algorithm for Dummies
Daniel Jiménez
Daniel Jiménez

Posted on • Edited on

Luhn Algorithm for Dummies

Are you crying until midnight trying to understand how to do the Luhn Algorithm?
Are you trying hard for hours and then giving up when your only error was about when to double?

This is your place. Here, I will explain to you how to do it with JavaScript. From a dummy to another dummy. Let's go.

What the #### is the Luhn Algorithm?


To make a long story short, it’s an algorithm used for validating credit cards. Basically, if at the end your result is 0, you have a valid card. If not, be ready because Ocean’s Eleven is entering your bank.

For implementing the algorithm in code, you have to take into consideration these 5 steps:

1) You need to iterate through each number from right to left (aka backwards).

2) Then, you multiply by 2 only the digits in even positions (starting from the right).

Imagine you have '2097'. We would multiply 9 and 2 by 2. The other numbers remain unchanged.

3) For the digits you’ve doubled, if they are greater than or equal to 10, you have to subtract 9 from them.

4) Now, it’s time to sum everything up.

5) You need to get the module of the division of your total sum by 10. The module is what’s left after division.

For example, if you divide 10 by 2, the result is 5 and the module is 0 because there’s nothing left. But if you divide 9 by 2, the result is 4 and the module is 1 because 2 * 4 is 8, and you’re missing 1 to reach 9.

Steps explained in a image

Luhn Algorithm Explanation


Let’s Code It in JavaScript!
Now, I will show you the complete code and then explain it. This first code is the best way to understand it because it’s quite raw. There are other ways of doing it with array methods, but let’s start with this first.

const luhnAlgorithm = (arr) => {
    let sum = 0;
    let shouldDouble = false;

    for (let i = arr.length - 1; i >= 0; i--) {
        let digit = arr[i];
        if (shouldDouble) {
            digit *= 2;
            if (digit > 9) digit -= 9;
        }
        sum += digit;
        shouldDouble = !shouldDouble;
    }

    console.log("Total sum:", sum);
    return sum % 10 === 0;
};

// Example credit card numbers (as arrays)
const validCreditCard = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]; // Valid
const invalidCreditCard = [3, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]; // Invalid

console.log(luhnAlgorithm(validCreditCard)); // true
console.log(luhnAlgorithm(invalidCreditCard)); // false
Enter fullscreen mode Exit fullscreen mode

Code Explanation


It wasn’t so hard, was it? I’ll explain it a little bit.

Step 1: The iteration from right to left is solved by using a for loop with a decrement (i--).

Step 2: We use a variable called shouldDouble, which is a boolean that changes in each iteration. It’s false in the beginning because the last number is never multiplied. Remember, that’s the reason why we start from the end.

Step 3: If a digit is greater than 9 after doubling, we subtract 9 from it: if (digit > 9) digit -= 9;. That’s all.

Step 4: We add the digit to the total sum: sum += digit;.

Step 5: The result is checked by returning sum % 10 === 0. If the remainder is 0, the credit card number is valid.

Alternative Solutions


There are other ways of solving this exercise that involve more methods. For example, you can use array methods like map, reduce, and reverse to achieve the same result. If you’re interested, check out this (https://www.30secondsofcode.org/js/s/luhn-check/) for an alternative implementation.

Top comments (0)