-1

I believe this is a scope problem, but idk why it's not working. I'm fairly new to js, tried checking the documentation but still couldn't solve it

For some reason, the "soma" variable always logs as "NaN" when inside the for loop. Prob is something simple, but i've been hitting my head on the desk for almost an hour now. Help D:

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
// Luhn Algorithm
validateCred = (array) => {
    var count = 0
    var soma = 0
    for (i=array.length; i != -1; i--) {
        if (count === 0) {
            count += 1
            soma += array[i]
        } else {
            if(array[i]*2 > 9) {
                soma += array[i]*2 - 9
            } else {
                soma += array[i]*2
            }
            count = 0
        }
        console.log(soma%10) // expected output === 0
    }
}

validateCred(valid1)
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Tiduzz99
  • 3
  • 2
  • 2
    `i=array.length` - this puts you out of bounds of the array at the start. Array indexes start from `0` and run until `array.length - 1` – VLAZ Jan 29 '21 at 22:24
  • in addition -your console log is inside the loop - your expectation is that it would be outside the loop. – Randy Casburn Jan 29 '21 at 22:25
  • Does this answer your question? [Reversed For Loop - First iteration undefined](https://stackoverflow.com/questions/41267096/reversed-for-loop-first-iteration-undefined) – Ivar Jan 29 '21 at 22:30

2 Answers2

2

Change the i=array.length to i=array.length - 1 & move your console.log after loop

const valid1 = [4, 5, 3, 9, 6, 7, 7, 9, 0, 8, 0, 1, 6, 8, 0, 8]
// Luhn Algorithm
validateCred = (array) => {
    var count = 0
    var soma = 0
    for (i=array.length - 1; i != -1; i--) {
        if (count === 0) {
            count += 1
            soma += array[i]
        } else {
            if(array[i]*2 > 9) {
                soma += array[i]*2 - 9
            } else {
                soma += array[i]*2
            }
            count = 0
        }
    }
     console.log(soma%10) // expected output === 0
}

validateCred(valid1)
Valentin
  • 144
  • 2
  • 7
1

The last item of an array is in the array.length-1 position, since the first element is in the 0 position that's why array[array.length] return nan.Besides you may want to read about the standard methods for iterate over an array : array.foreach(), array.filter(), array.reduce and array.map().

  • `array[array.length]` returns `undefined` not `NaN`. Also the part about the array prototype functions might be a bit misleading. `.filter()`, `.reduce()` and `.map()` have specific usages, they're not a replacement for a for-loop. Also neither of them (including `.forEach()`) iterate in reverse order. – Ivar Jan 29 '21 at 22:52
  • Well, that's truthy. – Edwin Sánchez Jan 29 '21 at 23:07