# Testing Luhn algorithm with JavaScript

I have created some JavaScript-code that tests a number according to the Luhn algorithm. It works the way it should. However, it is rather lengthy. I’m wondering if there’s a smart way to shorten the code? Sure, there are other ways to write the whole thing, but I do like this particular for-loop and the charAt() method, they are comprehensible to me. I would prefer to maintain the “tools” but still cut back on functions and possibly variables.

function luhnTest(userInput){

``````	var backwards = "";
var multiplyx2 = "";
var total = 0;

/* For-loop going through the number. It begins at the second digit from the end.
Then it adds to "backwards" every other digit going backwards through the number. */
for(i = userInput.length-2; i >= 0; i-=2){
backwards += userInput.charAt(i);
}

/* For-loop going through the digits in "backwards" and multiplying them by 2.
The multiplied digits are stored in "multiplyx2".*/
for(i = 0; i < backwards.length; i++){
multiplyx2 += backwards.charAt(i)*2;
}

/* The digits in "multiplyx2" are added up and stored in "total". */
for(i = 0; i < multiplyx2.length; i++){
total += parseInt(multiplyx2.charAt(i));
}

/* Adding up the digits that have been left out. Starting with the third digit from the end.
These digits are added to "total". */
for(i = userInput.length-3; i >= 0; i-=2){
total += parseInt(userInput.charAt(i));
}

/* Adding the last digit in the card number to "total".
Could have done so in previous loop but just for the sake of it (that's how the Luhn algorithm goes) . */
total += parseInt(userInput.charAt(userInput.length-1))

/* Testing if "total" can be divided by 10 without leaving a remainder. */
if((total % 10) == 0){
return true;
}
``````

}

Being readable all comes down to the individual coder.
There are shorter Luhn javascripts on wikipedia, I happened to see them when I read up on the algorithm.

I like when things are readable, so I like this type of scripts that you have done.

1 Like

I agree - readability totally trumps brevity unless there is a massive performance drawback or something That’s one of the reasons why I still don’t like arrow functions introduced as part of ES6 haha.