Credit Card Checker validateCred() help

Any suggestions, ideas are welcomed.

Whenever I call this function multiple times with valid arrays, the console logs all of the arrays as “Valid”, but when I call this function with an invalid array before the valid arrays, the console logs all of the arrays as “Invalid”. Why is it doing that?

let sumRemainNum = [];

function validateCred(array) {
 for (let index = 15; index >= 0; index--) {
   if (index % 2 === 0) {
     array[index]*2;
     if (array[index]*2 > 9) {
       sumRemainNum.push(array[index]*2-9);
     } else {
       sumRemainNum.push(array[index]*2);
     }
   } else {
     sumRemainNum.push(array[index]);
   }
 }
 let sum = sumRemainNum.reduce((a,b) => {return a+b});
 if (sum % 10 === 0) {
   console.log('Credit Card is Valid');
 } else {
   console.log('Credit Card is Invalid');
 }
}
1 Like

Your sumRemainNum array is declared outside of the function and you aren’t resetting it back to an empty array when you’re done with it (at least not in the code you posted).

This means that the values you are storing in there remain between calls, so 1 invalid card will start throwing everything off. You could log sumRemainNum.length to see it growing between calls.

3 Likes

Hey @shanellcarter7018442, did @selectall help answer your question?

1 Like

@shanellcarter7018442 ,

In addition to the issue pointed out by @selectall, how are you handling cards numbers with more or less than 16 digits?

This issue is actually part of the problem regarding your original question. As @selectall pointed out, your sumRemainNum array continues to grow with each call to your function, but the first 15 digits are all that you ever check, so if the first card has 15 digits, and is valid, everything you pass afterwards is going to evaluate to valid as well.

1 Like