Why does count go to -1 in the while loop?

  • 0
    let count = 10;
    
    while(count--) {
      //some code
    }
    
    console.log(count)


    As a result, count equals -1 after the loop. Although, in theory, with count === 0, the loop should stop, and 0 will be displayed in the console, which is what happens with this writing:

    let count = 10;
    
    while(count) {
      //some code
      count--
    }
    
    console.log(count)
    JavaScript Anonymous, Jul 21, 2019

  • 1 Answers
  • 0
    When you use postdecrement in a condition, something like 0-- happens, and naturally 0 becomes false , but after the condition count is decremented. If you want to decrease the number right in the condition, use a pre-decrement:

    let count = 10;

    while (--count) {}

    console.log(count)
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!