Javascript while loops - why is this simple code producing an infinite loop

I have an infinite loop and I’m not sure why. Sorry, I’m super new and while I’m understanding what syntax looks like and all, I’m playing around with numbers and stuff just trying to figure out what goes where and why. Variables have always thrown me for a loop - pun sorta intended. Anyway, why does this cause an infinite loop?

let lessThan5 = true;
let j = 0;

while(lessThan5) {
  if (j < 2) {
    j++;
  } else if (j >= 5) {
    lessThan5 = false;
  }
  console.log(lessThan5)
  }

I’ve written it out slowly with pen and paper and don’t really get it. To the best of my limited understanding of math, it should return 1 the first time around, then 2, then … if j >=5 wouldn’t that create a gray area in between 2 and 5 or something? Like if j is greater than or equal to 5, j would never get to 5 so why doesn’t that just return false or undefined or something? Or if the answer is an impossibility why not Nan? Why the infinite loop?

Hello @cloud3713707089, welcome to the forums!
The reason there’s an infinite loop is because j is only incremented when it is less than 2. Once it reaches 2, it doesn’t increment (and so the else if block never runs), meaning lessThan5 remains true for ever…

3 Likes

awesome, thank you! as I was writing the question I’m thinking maybe that’s the answer, but I needed to know for sure! So if there was an else if for anything between 2 and 5 then it would have something to run but since it doesn’t then it just goes off the first if statement and that’s it, then, yeah? I’ll go try it, thanks!!!

1 Like

but also, a random question: can you just “see” what it outputs? I know this is a super simple one, but you probably don’t even need to test it out, can you just see what’s wrong with it? that’s so wild, if so.

Sometimes I can (especially if it’s a problem I’ve seen often), but, no, I did have to run this one-it’s pretty tricky to spot!

haha that’s so cool! thank you for your help!! I really appreciate it. I have such simple weird little questions, this is gonna take me forever to get through!!!

No problem; I’m happy to help! No one starts this journey knowing everything, but as long as you’re understanding (especially by asking plenty of questions), then it means you’re making good progress!
Happy coding!

2 Likes