# Why does my code run endlessly despite not having a while loop?

I’ve written this code for the 3rd project requirement which is to write the ‘validateCred()’ function but when I run my code it will not log anything to the console and runs endlessly no matter how long I wait. The code is below:

const validateCred = array => {

let tempArray = array;

for(let i = array.length - 2; i >= 0; i - 2) {

``````tempArray[i] *= 2;

if(tempArray[i] > 9)

tempArray[i] -= 9;
``````

}

let num = 0;

const sum = tempArray.forEach(number => num += number);

if((sum % 10) === 0)

``````return true;
``````

return false;

}

console.log(validateCred(valid1));

console.log(validateCred(invalid1));

console.log(validateCred(mystery1));

You have to reassign i. The way you’ve written it, i will always be array.length - 2. You can fix that by writing i-=2.

1 Like

A while loop isn’t the only way to get an infinite loop, it’s just the easiest! The main condition for an endless loop is just that the loop can never meet it’s end condition. In this case, your for loop has the end condition of `i >= 0` i.e. if i is less than 0 then the loop will end. Therefore we know there must be some reason this is never triggering.

The reason is around the increment section in your loop declaration. An important thing to note is that when we do a normal for loop, we usually use `i++` or `i--`. These operators do the same job as writing `i = i + 1` or `i = i - 1`. However in your case you have written `i - 2`. This is not assigning back to i a value, and as such the value of i actually never changes. What you want to do instead is `i -= 2`, which is equivalent to `i = i - 2` and this should fix your problem.

3 Likes

This indeed was the problem. Thanks!