Snackaholic
Snackaholic

Reputation: 610

Why does the while loop stop when condition check variable becomes 0?

Could someone explain me what happens down below?

var i = 5;
while(--i){
  console.log(i);
}

The thing is the while loop goes until 1 (console logs 4,3,2,1)

I know that if I check 1 or 0 for true I will get the following result

0 == true > false

1 == true > true

What I dont understand is what happens when the number is something like 4? How does that even work?

Since checking 4 for true will deliver the following result

4 == true > false

Upvotes: 2

Views: 307

Answers (2)

AndrewPolland
AndrewPolland

Reputation: 3071

Any non-zero number is treated as TRUE.

So in your loop, i starts as 5. On the first iteration i is reduced by 1 (by the --i), and the result (4) is tested to be TRUE. Thus it enters the WHILE loop and logs the value of i (4). The WHILE loop then returns to start and reduces the value of i by 1 again to become 3. This is also treated as TRUE and thus enters the loop again.

Only once i reaches 0 does it get treated as FALSE, and thus exits the WHILE loop.

Upvotes: 2

Chris Charles
Chris Charles

Reputation: 4446

As commented above:

4 is a truthy value in javascript:

if (4) {
    console.log(true);    
} else {
    console.log(false);
}

this will print true

Another way to see this:

0 and true = false
1 and true = true
4 and true = true

Documentation for truthy: https://developer.mozilla.org/en/docs/Glossary/Truthy

In JavaScript, a truthy value is a value that translates to true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN).

The reason that 4 != true is that the true value is coerced into a number. So infact 4 == true + true + true + true

Upvotes: 3

Related Questions