Someone once said that the boolean value for 0 is false but in this very short, simple and precise code, the output is 2, why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Someone once said that the boolean value for 0 is false but in this very short, simple and precise code, the output is 2, why?

var x = 0; if(!true) { x = 1 } else { x = 2 }

8th Jul 2019, 8:52 PM
eMBee
eMBee - avatar
7 Answers
+ 16
if condition in if() statement evaluates to true then only if() block executes. if(true){ //statement(s) in this block will execute } if(false){ //statement(s) in this block will NOT execute }
8th Jul 2019, 9:18 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 13
!true means false, !(NOT) operator changes true to false & false to true. thatswhy else block get executed & value of x becomes 2
8th Jul 2019, 9:02 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 4
Okay, Gaurav Agrawal, I think I understand your answer but if you look at the code again, it says "if false" and since 0 is false then x should be 1. Or what do you think? 🤷‍♂️
8th Jul 2019, 9:08 PM
eMBee
eMBee - avatar
+ 4
\o/, I love your answer 🤣👍, nice one
8th Jul 2019, 10:55 PM
eMBee
eMBee - avatar
+ 3
You are not checking if x is false, you are using an if-statement that is always false. If you want to check if x is false, you should use if(x == false) or simply if(!x). In both examples, x would be false and the else block would be executed, making x receive 2 as its new value.
8th Jul 2019, 9:33 PM
AT-Low
AT-Low - avatar
8th Jul 2019, 10:35 PM
\•/
\•/ - avatar
+ 1
😄
9th Jul 2019, 12:29 PM
\•/
\•/ - avatar