Credit card checker project

Hi guys can anyone tell me whats wrong with my counter variable. I want it to go up by 1 each time the code inside the for loop is executed. Instead it just stays at 1 lol. Here is a link if you want to understand the purpose of the function Luhn algorithm - Wikipedia.

const validateCred = arr => { let sum = 0; for (let i = arr.length - 1; i >= 0; i--) { console.log(sum) let counter = 0; counter ++; console.log(counter) if (counter % 2 === 0) { let doubled = arr[i] * 2; if (doubled > 9) { doubled -= 9; sum += doubled; } else { sum += doubled; } } else sum += arr[i]; } if (sum % 10 === 0) { return true; } else { return false; } } const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]; console.log(validateCred(valid1))

You’ve declared the counter inside the loop and set it to the value of 0. Therefore every time the loop cycles round, it sets counter to 0 and then increments it. You need to declare counter outside of the loop first, and then it should work correctly!

1 Like

Literally just as you replied I figured it out myself haha. Cheers buddy

1 Like