3

Let's see the example code:

 var limit = 3;
 while(limit--){
   console.log(limit);
   if(limit){
     console.log("limit is true");
   }else{
     console.log("limit is false")
   }
 }

and the output will be:

2
"limit is true"
1
"limit is true"
0
"limit is false"

There is a 0, which means false in the last time while condition. Why the last time loop will execute?

Newman
  • 33
  • 5

5 Answers5

8

limit-- It is a post decrement. So when the limit is at 1 it resolves to true inside while and then it is actually decrementing hence when you printing it is 0.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3
while(limit--) 

equals

while(limit){
    limit = limit -1;
}

so the limit is from 3 to 1 in while expression, while in braces, limit is from 2 to 0, so 'limit is false' will be executed. if you expect 'limit is false' doesn't execute, you can replace limit-- with --limit

刘思凡
  • 423
  • 2
  • 14
3

As you are using post increment it will first check condition and then will perform decrement on that variable so here while(limit--) will be treated as while(limit).

DRY RUN:

var limit = 3;

first time:

while(limit--){     //check limit while limit = 3 returns true and then decrement by 1 
   console.log(limit);  //so now print limit as 2
   if(limit){  //check limit while limit = 2
     console.log("limit is true");  //so now print this one
   }else{
     console.log("limit is false")
   }
 }

second time:

while(limit--){     //check limit while limit = 2 returns true and then decrement by 1 
   console.log(limit);  //so now print limit as 1
   if(limit){     //check limit while limit = 1
     console.log("limit is true");  //so now print this one
   }else{
     console.log("limit is false")
   }
 }

third time:

while(limit--){     //check limit while limit = 1 returns true and then decrement by 1 
   console.log(limit);  //so now print limit as 0
   if(limit){     //check limit while limit = 0
     console.log("limit is true");  
   }else{
     console.log("limit is false")  //so now print this one
   }
 }

fourth time:

it will not go in while loop as now limit = 0

Chirag Jain
  • 628
  • 11
  • 24
0

In several languages, 0 value is considered as a false value.

Also limit-- makes the decrement after being evaluated by the while condition.

ADreNaLiNe-DJ
  • 4,787
  • 3
  • 26
  • 35
0

Here is a good way to look at it. We're looking at a number and seeing if it's above 0 before if it is we're taking away 1 and then running through the loop again otherwise we're stopping there.

let three = 3, two = 2, one = 1, zero = 0;

console.log('3--: ' + (three-- > 0));
console.log('2--: ' + (two-- > 0));
console.log('1--: ' + (one-- > 0));
console.log('0--: ' + (zero-- > 0));
Andrew Bone
  • 7,092
  • 2
  • 18
  • 33