Very clean Luhn Algorithm code // How does he do it?

So I have (finally) completed the Credit Card Checker project, which can be found here

While doing some research for the project, I came cross and found this very clean code (below) for validating credit cards using the Luhn algorithm. My question is, how does he use the var doubleUp = false; in order to double every other number in the array (as the algorithm specifies)? Thanks in advance!

/* Luhn Algorithm JavaScript by */

function LuhnAlgorithm(num){

    var inputNum = num.toString();
    var sum = 0;
    var doubleUp = false;

    /* from the right to left, double every other digit starting with the second to last digit.*/
    for (var i = inputNum.length - 1; i >= 0; i--)
        var curDigit = parseInt(inputNum.charAt(i));

        /* double every other digit starting with the second to last digit */
            /* doubled number is greater than 9 than subtracted 9 */
            if((curDigit*2) > 9)
              sum +=( curDigit*2)-9;
              sum += curDigit*2;
          sum += curDigit;
        var doubleUp =!doubleUp

  /* sum and divide it by 10. If the remainder equals zero, the original credit card number is valid.  */
  return (sum % 10) == 0  ? true : false;


Notice that var doubleUp = !doubleUp is outside the if/else statements, and will execute with every pass of the for loop. So doubleUp is initialized to false, then every iteration of the for loop will flip the value to true, false, true, … Remember that ! is a logical operator that means “not [whatever comes after]”. It inverts true to false and false to true.


ah ha! Thank you so much. So, what I failed to remember is that doubleUp =!doubleUp is not the same as doubleUp !== doubleUp. So now it’s making more sense. And because doubleUp is set to false to begin with, then it will always skip the first number it checks.

My next question though is why he uses num.toString() to then later use parseInt to convert it back to a number value at var curDigit = parseInt(inputNum.charAt(i));? Where is the logic here? Could he not just have assigned inputNum to an array?

Since you are trying to access individual digits in a long number, my guess is that the author of the code thought it would be easier to convert the number to a string so that he/she could pick each character of the string easily with .charAt() and then the author had to convert it back to an integer to do math with it

1 Like

cool. Thinking about it myself, and based off my limited knowledge, I guess I would have reached for the .forEach function and .pushed each to an array.

Thanks for your help and clarification. It is very illuminating to get insight into other’s techniques.