WebReference.com - Chapter 10 selections: Practical JavaScript for the Usable Web from glasshaus (4/5). | WebReference

WebReference.com - Chapter 10 selections: Practical JavaScript for the Usable Web from glasshaus (4/5).

To page 1To page 2To page 3current pageTo page 5
[previous] [next]

Practical JavaScript for the Usable Web

First we check if isValid is true (that is, if all other checks so far proved satisfactory). Then, after our variable declarations, we have the main for loop that will go through the credit card number a digit at a time starting with the last digit and moving to the first.

   if (isValid)
   {
     var numberProduct;
     var numberProductDigitIndex;
     var checkSumTotal = 0;
     for (digitCounter = cardNumberLength - 1;
       digitCounter >= 0;
       digitCounter--)

In this for loop we do a number of things. Firstly we add a digit's value to the running total, checkSumTotal.

       checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));

Then we move to the digit that is one nearer the start of the card number string. We multiply this next digit by 2.

       digitCounter--;
       numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));

We take the digits forming the results of the product calculation and in the inner for loop we add these digits to the running total.

       for (var productDigitCounter = 0;
         productDigitCounter < numberProduct.length;
         productDigitCounter++)
       {
         checkSumTotal +=
          parseInt(numberProduct.charAt(productDigitCounter));
       }

Our outer for loop continues by moving to the next digit to the left, and iterates until we reach the first digit in the credit card number string.

If we think back to the explanation of the Luhn formula, our approach is out of step in that we are not doing step 1, then step 2, and so on, but instead are merging steps 1 – 4 and processing the number on a digit by digit basis, keeping a running total. It amounts to exactly the same thing, but reduces the number of loops required. Let's summarize the steps in our outer and inner for loops:

To page 1To page 2To page 3current pageTo page 5
[previous] [next]

Created: April 15, 2002
Revised: April 19, 2002


URL: http://webreference.com/programming/javascript/practical/chap10/4.html