Why does my Luhn Algorithm checker keep crashing/looping?

Hi! My Creditcard checker keeps crashing on what appears to me to be simple forloops. I can only imagine its the fault of the actual checker function, but I’ve made sure it only returns single digits?

// An array of all the arrays above
const batch = [valid1, valid2, valid3, valid4, valid5, invalid1, invalid2, invalid3, invalid4, invalid5, mystery1, mystery2, mystery3, mystery4, mystery5];

// Add your functions below:
const validateCred = arr => {
  let temp = [];
  for(i = arr.length-1; i >= 0; i--) {
    if (i % 2 === 0) {
      if ((arr[i] * 2) > 9) {
        temp.push((arr[i] * 2) - 9);
      } else {
        temp.push(arr[i] * 2);
    } else {
  sum = (temp.reduce((a, b) => a + b, 0)) % 10;
  return sum

const findInvalidCards = (nestedArray) => {
  let invalidCards = [];
  // test
  for(i = 0; i < nestedArray.length; i++) {

Define crashing, are you getting any errors? What do they say?

Hey, I ran your code. You may want to look into your variable (re)assignments.

Besides that I notice you are not entirely following the instructions.

validateCred should return true or false based on the validity of a card.

1 Like

Hey, thanks for looking at this. I realise now I stuck a mixed up, troubleshooting version of the program, I’m aware its off track.

What I don’t understand is why the validateCred function produces a single digit according to outcome of the modulo operation. I expected the following loop function to simply output (in this case) to the console a series of single digits.

That said, I don’t really understand the .reduce method I used. That’s the only assignment that I wouldn’t be able to make a guess on.

array.reduce is a very simple for-loop. try implementing it. (if you pay attention to the input and output of the things involved it shouldn’t be much of a mystery how it’s done)

If you return something mod 10 then that’s going to be a single digit. no reason to expect multiple things there.

If you get the wrong result for a card I suggest carrying out the algorithm manually to see if you get the correct result then. And if you do, then start comparing what you did manually to what steps are being carried out in your code, you can for example print out the steps that you are carrying out.