Aref
Aref

Reputation: 1

while(i) loop in JavaScript

I ran the below code in JavaScript

let i = 3;
while (i) {
    console.log(i--);
}

since the while(i) is not like while(i>0) then I expected the result as 3,2,1,0,-1,-2,...

but the actual result is 3,2,1. Could anyone explain this case to me? I am confused.

Upvotes: 0

Views: 91

Answers (2)

Neville Nazerane
Neville Nazerane

Reputation: 7019

While loops run until its condition is set false. Note that all statements such as while, if and ternaries all handle conditions in the same way. To have a better understanding on how the simplest and quickest way is to test them with ternaries.

I usually run something such as the following on a js console such as chrome (ctrl + j)

1?2:3;
0?2:3;
5?2:3;
"Hello"?2:3;
""?2:3;

And so on. These are conditional statements, the first number is taken as a condition, the second (2) is what will be returned if it were true, and the third (3) is what it will return if it were false. Note that 2 and 3 are just random numbers.

In the example you have shown, i is an integer. For an integer, only 0 is taken as a false.

Upvotes: -1

nipuna-g
nipuna-g

Reputation: 6652

The while loop runs until the check condition is false.

In this case, it is the value of i.

Since Javascript is dynamically typed(ie - we don't define the types when defining the variables) the value of i is converted into a boolean from the type it is currently in.

In this case, you are setting numerical values to i. And the number 0 is considered to be falsely. Therefore, breaking the while loop.

You can refer here for a full list of falsely value.

Upvotes: 2

Related Questions