0

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.

Pang
10.2k146 gold badges87 silver badges126 bronze badges
asked Dec 6, 2017 at 3:27
1
  • 3
    when i == 0, i is "falsey" ... other things that are falsey are, an empty string, NaN, false, undefined, null Commented Dec 6, 2017 at 3:28

2 Answers 2

2

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.

answered Dec 6, 2017 at 3:39
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Totally understood. I am a beginner in JavaScript.
-1

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.

answered Dec 6, 2017 at 3:36

3 Comments

Not quite sure what ternaries have to do with either while loops or truthiness, but it is true that 0 is the only falsey integer .
Confusing answer, even when you understand OP's issue and also understand ternaries
ternaries helped me understand how such things work in js including while loops. I updated the answer. let me know if you guys still don't see a connection.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.